我想我需要像 ruby 的 splat *
这样的东西。
function foo() {
var result = '';
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
function bar() {
return foo(arguments) // this line doesn't work as I expect
}
bar(1, 2, 3);
我希望它返回 "123"
,但我得到的是 "[object Arguments]"
。我想这是有道理的。它传递的是表示参数的对象,而不是单独的参数。
那么我如何简单地将任意数量的参数转发给另一个接受任意数量参数的函数呢?
更新:从 ES6 开始,您可以使用 spread syntax调用函数,将可迭代对象的元素应用为函数调用的参数值:
function bar() {
return foo(...arguments);
}
请注意,您还可以接收可变数量的参数作为实际数组,而不是使用arguments
对象。
例如:
function sum(...args) { // args is an array
return args.reduce((total, num) => total + num)
}
function bar(...args) {
return sum(...args) // this just forwards the call spreading the argument values
}
console.log(bar(1, 2, 3)); // 6
在 ES3/ES5 时代,要正确地将参数传递给另一个函数,您需要使用 apply
:
function bar() {
return foo.apply(null, arguments);
}
apply
方法有两个参数,第一个是thisObj
,它的值会作为this
里面的值调用函数,如果使用null
或undefined
,函数内部的this
值将引用全局对象,在非严格模式下,否则为 undefined
。
apply
期望的第二个参数是一个类似数组的对象,其中包含要应用于函数的参数值。
检查上面的例子here .