为什么我的JavaScript函数接受三个数组,而不是一个包含三个数组的数组?

编程入门 行业动态 更新时间:2024-10-09 21:20:32
本文介绍了为什么我的JavaScript函数接受三个数组,而不是一个包含三个数组的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 function product() { return Array.prototype.reduce.call(arguments, function(as, bs) { return [a.concat(b) for each (a in as) for each (b in bs)] }, [[]]); } arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']]; alert(product(['4','4A','4B'],['16D','15D'],['5d','5e']);

以上情况有效,但以下情况不起作用:

The above works but the following don't work:

arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']]; alert(product(arr4);

感谢您的建议

推荐答案

你可以有一个或者另一个;否则它的定义很差。(除非你想做一个非常可疑的决定做特殊套管,如果如果我的第一个论点是数组和每个元素都是一个数组,返回不同的东西。然后你将立即重建PHP。=])

You can have either one or the other; otherwise it's poorly defined. (Unless you want to make the very questionable decision to do special-casing like "if my first argument is an array and each element is an array, return something different". Then you'll be remaking PHP in no time. =])

使用 somefunction .apply 方法;这就是它的用途。例如:

Use the somefunction.apply method instead; that's what it was made for. For example:

product.apply(this, arr4)

相当于:

product(arr4[0], arr4[1], ...)

如果你经常这么做,你可以定义 product2(数组){return product.apply(this,arrays)} 。

If you do this a lot, you can define product2(arrays) {return product.apply(this,arrays)}.

但是,除非你想两者 产品([..],[..] ,. 。)和产品([[..],[..],..]),这看起来不太优雅。

However unless you want to do both product([..], [..], ..) and product([[..],[..],..]), this seems inelegant.

如果你希望这个函数默认表现如 product([[..],[..],..]) ,那么解决这个问题的正确方法是修改功能以满足您的需求。它目前使用默认的variadic(多个参数)参数变量特殊于javascript,它代表一个数组,表示传递给函数的所有参数。如果你想要普通式固定数量的参数函数,这不是你想要的。首先添加适当的参数:

If you want this function to behave by default like product([[..],[..],..]), then the correct way to solve this is to modify the function to suit your needs. It is currently using the default "variadic" (multiple arguments) arguments variable special to javascript, which stands for an array representing all the arguments you passed into the function. This is not what you want, if you want normal-style fixed-number-of-arguments functions. First add in the appropriate parameter:

function product(arrays) { ... }

而不是使用默认的参数变量,用数组替换。

and rather than using the default arguments variable, replace that with arrays.

更多推荐

为什么我的JavaScript函数接受三个数组,而不是一个包含三个数组的数组?

本文发布于:2023-11-29 09:58:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646072.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   是一个   而不   函数   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!