为什么我的 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']);
以上有效,但以下无效:
arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(arr4);
感谢您的建议
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以选择其中之一;否则它的定义不明确。 (除非你想做出非常可疑的决定来进行特殊情况处理,例如“如果我的第一个参数是一个数组并且每个元素都是一个数组,则返回不同的东西”。那么你将立即重新制作 PHP。=])
使用 somefunction.apply 方法反而;这就是它的目的。例如:
相当于:
如果您经常这样做,则可以定义
product2(arrays) {return Product.apply(this,arrays)}
。但是,除非您想要两者
product([..], [..], ..)
和product([[..],[. .],..])
,这看起来不太优雅。如果您希望此函数默认的行为类似于
product([[..],[..],..])
,那么解决此问题的正确方法是修改该函数以适合您的需求需要。它当前使用 javascript 特有的默认“variadic”(多个参数)arguments
变量,它代表一个数组,表示您传递给函数的所有参数。如果您想要普通风格的固定参数数量函数,这不是您想要的。首先添加适当的参数:不要使用默认的参数变量,而是将其替换为数组。
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:
Is equivalent to:
If you do this a lot, you can define
product2(arrays) {return product.apply(this,arrays)}
.However unless you want to do both
product([..], [..], ..)
andproduct([[..],[..],..])
, 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:and rather than using the default
arguments
variable, replace that witharrays
.