在 JavaScript 中将数组作为函数参数传递 [英] Passing an array as a function parameter in JavaScript
本文介绍了在 JavaScript 中将数组作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用数组作为参数调用函数:
I'd like to call a function using an array as parameters:
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()
中?
Is there a better way of passing the contents of x
into call_me()
?
推荐答案
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
有关函数的信息,请参阅 MDN 文档.prototype.apply()
.
如果环境支持ECMAScript 6,可以使用传播参数:
If the environment supports ECMAScript 6, you can use a spread argument instead:
call_me(...args);
这篇关于在 JavaScript 中将数组作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文