问题
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);
Thanks for suggestions
回答1:
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. =])
Use the somefunction.apply method instead; that's what it was made for. For example:
product.apply(this, arr4)
Is equivalent to:
product(arr4[0], arr4[1], ...)
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.
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
.
来源:https://stackoverflow.com/questions/9385755/why-does-my-javascript-function-accept-three-arrays-but-not-an-array-containing