在JavaScript中将数组作为函数参数传递

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)

  • 作为旁注,如果有人想要传递一个关联数组(命名键),那么使用一个对象.来自PHP(并且总是由谷歌推出这个帖子)这花了我一段时间才弄明白.您可以将整个对象作为参数传递.http://www.w3schools.com/js/js_objects.asp (7认同)

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)

  • +1因为即使它没有回答原始问题,也可能是看过这个页面的100K +人正在寻找的东西. (57认同)
  • 这是因为我无法修改call_me().它在其他一些库中定义,不可能搞乱API. (34认同)

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之外,所有主流浏览器都支持它.

扩展运算符可以执行许多其他有用的操作,链接的文档可以很好地显示它.

  • 新链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax (2认同)

小智 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)

  • 这是一种不好的做法......如果你看一下这个函数,你将无法看到函数需要什么,每个参数都是可选的. (2认同)

vsy*_*ync 6

函数参数也可以是数组:

function foo([a,b,c], d){
  console.log(a,b,c,d);
}

foo([1,2,3], 4)
Run Code Online (Sandbox Code Playgroud)

当然也可以使用spread

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)