我想调用一个函数使用数组作为参数:
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()?
当前回答
为什么不传递整个数组并在函数中根据需要处理它呢?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
其他回答
你可以在更基本的形式中使用展开运算符
[].concat(...array)
对于返回数组但希望作为参数传递的函数
例子:
function expectArguments(...args){
return [].concat(...args);
}
JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))
您可以使用扩展语法
例如:
函数打印(…inpu) { console.log(…inpu) } Var arry = ['p0','p1','p2'] 打印(…进行)
链接如下:modzilla传播语法参考文档
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
请参阅MDN文档中的Function.prototype.apply()。
如果环境支持ECMAScript 6,你可以使用spread参数:
call_me(...args);
正如@KaptajnKold回答的那样
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
你也不需要为call_me函数定义每个参数。 你可以用参数
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
为什么不传递整个数组并在函数中根据需要处理它呢?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}