[英] Passing an array as a function parameter in JavaScript
我想使用数组作为参数调用函数:
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 argument:
call_me(...args);