Rob*_*ert 279 javascript arrays function call
我想使用数组作为参数来调用函数:
const x = ['p0', 'p1', 'p2'];
call_me(x[0], x[1], x[2]); // I don't like it
function call_me (param0, param1, param2 ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
有路过的内容的一种更好的方式x进入call_me()?
Kap*_*old 400
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
Run Code Online (Sandbox Code Playgroud)
请参阅MDN文档Function.prototype.apply().
如果环境支持ECMAScript 6,则可以使用spread参数:
call_me(...args);
Run Code Online (Sandbox Code Playgroud)
Kar*_*han 102
为什么不传递整个数组并根据需要在函数内处理它?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
Run Code Online (Sandbox Code Playgroud)
ple*_*xer 42
假设call_me是一个全局函数,所以你不要指望设置它.
var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
Run Code Online (Sandbox Code Playgroud)
Bol*_*Key 37
在ES6标准中,有一个新的扩展运算符 ...就是这样做的.
call_me(...x)
Run Code Online (Sandbox Code Playgroud)
除IE之外,所有主流浏览器都支持它.
扩展运算符可以执行许多其他有用的操作,链接的文档可以很好地显示它.
小智 6
正如@KaptajnKold回答的那样
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
Run Code Online (Sandbox Code Playgroud)
而且您不需要为call_me函数定义每个参数.你可以使用arguments
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
Run Code Online (Sandbox Code Playgroud)
function foo([a,b,c], d){
console.log(a,b,c,d);
}
foo([1,2,3], 4)Run Code Online (Sandbox Code Playgroud)
function foo(a, b, c, d){
console.log(a, b, c, d);
}
foo(...[1, 2, 3], 4)Run Code Online (Sandbox Code Playgroud)
小智 6
在使用扩展运算符时,我们必须注意它必须是最后一个或唯一传递的参数。否则会失败。
function callMe(...arr){ //valid arguments
alert(arr);
}
function callMe(name, ...arr){ //valid arguments
alert(arr);
}
function callMe(...arr, name){ //invalid arguments
alert(arr);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要传递一个数组作为起始参数,您可以执行以下操作:
function callMe(arr, name){
let newArr = [...arr];
alert(newArr);
}
Run Code Online (Sandbox Code Playgroud)