我想调用一个函数使用数组作为参数:
const x = ['p0', 'p1', 'p2'];
call_me(x[0], x[1], x[2]); // I don't like it
function call_me (param0, param1, param2 ) {
// ...
}
是否有更好的方法将x的内容传递给call_me()?
我想调用一个函数使用数组作为参数:
const x = ['p0', 'p1', 'p2'];
call_me(x[0], x[1], x[2]); // I don't like it
function call_me (param0, param1, param2 ) {
// ...
}
是否有更好的方法将x的内容传递给call_me()?
当前回答
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
请参阅MDN文档中的Function.prototype.apply()。
如果环境支持ECMAScript 6,你可以使用spread参数:
call_me(...args);
其他回答
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
请参阅MDN文档中的Function.prototype.apply()。
如果环境支持ECMAScript 6,你可以使用spread参数:
call_me(...args);
函数参数也可以是数组:
函数foo([a,b,c], d){ console.log (a, b, c, d); } foo((1、2、3)、4)
当然也可以用spread:
函数foo(a, b, c, d){ Console.log (a, b, c, d); } foo(…[1,2,3], 4)
您可以使用扩展语法
例如:
函数打印(…inpu) { console.log(…inpu) } Var arry = ['p0','p1','p2'] 打印(…进行)
链接如下:modzilla传播语法参考文档
为什么不传递整个数组并在函数中根据需要处理它呢?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
在使用展开运算符时,必须注意它必须是传递的最后一个或唯一一个参数。否则就会失败。
function callMe(...arr){ //valid arguments
alert(arr);
}
function callMe(name, ...arr){ //valid arguments
alert(arr);
}
function callMe(...arr, name){ //invalid arguments
alert(arr);
}
如果你需要传递一个数组作为起始参数,你可以这样做:
function callMe(arr, name){
let newArr = [...arr];
alert(newArr);
}