Javascript:转发采用可变数量参数的函数调用 [英] Javascript: Forwarding function calls that take variable number of arguments
问题描述
我想我需要像 ruby 的 splat *
之类的东西.
I think I need something like ruby's splat *
here.
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]"
.我想这是有道理的.它传递的是代表参数的对象,而不是单独的参数.
I want this to return "123"
, but instead I get "[object Arguments]"
. Which makes sense, I suppose. It's passing the object that represents the arguments, but not the arguments individually.
那么我如何简单地将任意数量的参数转发给另一个接受任意数量参数的函数?
So how do I simply forward any number of arguments to another function that takes any number of arguments?
推荐答案
更新: 从 ES6 开始,您可以使用 扩展语法来调用函数,将可迭代对象的元素应用为函数调用:
UPDATE: Since ES6, you can use the spread syntax to call a function, applying the elements of an iterable object as argument values of the function call:
function bar() {
return foo(...arguments);
}
请注意,您还可以接收可变数量的参数作为实际数组,而不是使用 arguments
对象.
Note that you can also receive a variable number of arguments as a real array, instead of using the arguments
object.
例如:
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 时代,要将参数正确传递给另一个函数,您需要使用 申请
:
In the days of ES3/ES5, to correctly pass the arguments to another function, you needed to use apply
:
function bar() {
return foo.apply(null, arguments);
}
apply
方法有两个参数,第一个是thisObj
,它的值将用作this
被调用的函数,如果使用null
或undefined
,函数内部的this
值将引用全局对象,在非严格模式下,否则为 undefined
.
The apply
method takes two parameters, the first is the thisObj
, the value of it will be used as the this
value inside the invoked function, if you use null
or undefined
, the this
value inside the function will refer to the global object, in non-strict mode, otherwise is undefined
.
apply
期望的第二个参数是一个类似数组的对象,其中包含要应用于函数的参数值.
The second argument that apply
expects is an array-like object that contains the argument values to be applied to the function.
在此处检查上述示例.
这篇关于Javascript:转发采用可变数量参数的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!