为什么我的JavaScript函数接受三个数组,而不是一个包含三个数组的数组? [英] Why does my JavaScript function accept three arrays, but not an array containing three arrays?
问题描述
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 取而代之的是a>方法;这就是它的用途。例如:
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函数接受三个数组,而不是一个包含三个数组的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!