Update:从 ES6 开始,您可以简单地使用扩展语法 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax调用函数时:
func(...arr);
由于 ES6,如果您希望将参数视为数组,您还可以在参数列表中使用扩展语法,例如:
function func(...args) {
args.forEach(arg => console.log(arg))
}
const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)
您可以将其与普通参数结合使用,例如,如果您想分别接收前两个参数,其余作为数组:
function func(first, second, ...theRest) {
//...
}
也许对您有用,您可以知道函数需要多少个参数:
var test = function (one, two, three) {};
test.length == 3;
但无论如何你可以传递任意数量的参数......
扩展语法比apply
如果您不需要设置this
函数调用中的值,这就是要走的路。
这是一个apply https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Function:apply例如,这是以前的方法:
var arr = ['a','b','c'];
function func() {
console.log(this); // 'test'
console.log(arguments.length); // 3
for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
};
func.apply('test', arr);
现在我只推荐使用apply
仅当您需要从数组传递任意数量的参数时and设置this
value. apply
需要的是this
value 作为第一个参数,如果我们使用,它将在函数调用中使用null
在非严格代码中,this
关键字将引用内部的全局对象(窗口)func
,在严格模式下,当显式使用 'use strict' 或在 ES 模块中时,null
将会被使用。
另请注意,arguments https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/argumentsobject 并不是真正的数组,您可以通过以下方式转换它:
var argsArray = Array.prototype.slice.call(arguments);
在 ES6 中:
const argsArray = [...arguments] // or Array.from(arguments)
但你很少使用arguments
由于扩展语法,现在可以直接对象。