简体   繁体   English

将数组中的所有值作为参数传递给函数

[英]Pass all the values from an array into a function as parameters

I have an array of values: 我有一系列值:

['a', 'b', 'c', 'd']

and I need to pass these as parameters to a function: 我需要将这些作为参数传递给函数:

window.myFunction('a', 'b', 'c', 'd');

This would be easier if I could just pass the array/object into the function, but the functions are written by other people or already exist and I cannot change them - they need to be passed as individual parameters, which is what I need solved. 如果我可以将数组/对象传递给函数,这会更容易,但函数是由其他人编写的或者已经存在而且我无法更改它们 - 它们需要作为单独的参数传递,这是我需要解决的问题。

The number of values being passed is not consistent. 传递的值的数量不一致。 It may be one, it may be 100. 它可能是一个,可能是100个。

Again, I cannot affect the functions. 再次,我不能影响功能。 They are how they are, and I will always receive an array of values to pass into them. 它们就是这样,我总会收到一系列值传递给它们。

Use the .apply method of the Function object. 使用Function对象的.apply方法。

window.myFunction.apply(window, ['a','b','c','d']);

The .apply method invokes the function you're calling, but lets you set the function's this value (the first argument) and lets you set its arguments using an Array (the second argument). .apply方法调用您正在调用的函数,但允许您设置函数的this值(第一个参数),并允许您使用Array(第二个参数)设置其参数。

So here we kept window as the this value, and we're passing the Array as the individual arguments. 所以这里我们将window保持为this值,我们将Array作为单独的参数传递。 The Array members will be distributed as though they were passed as individual arguments, so it's as if you had done this: Array成员将作为单独的参数传递,就好像你已经这样做了:

window.myFunction('a','b','c','d');

尝试

window.myFunction.apply(window, ['a', 'b', 'c', 'd']);

In ES6 you can use spread syntax. 在ES6中,您可以使用扩展语法。

As from Docs : 来自Docs

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. Spread语法允许在可能需要零个或多个参数(用于函数调用)或元素(用于数组文字)的位置扩展数组表达式或字符串等迭代,或者在零或更多位置扩展对象表达式键值对(对象文字)是预期的。

Your syntax will be: 你的语法是:

var array = ['a', 'b', 'c', 'd'];
myFunction(...array);

Demo: 演示:

 var array = ['a', 'b', 'c', 'd']; myFunction(...array); function myFunction(p1, p2, p3, p4) { console.log(p1, p2, p3, p4); } 

Array.prototype.map() Array.prototype.map()

 var arr = ['a','b','c']; function echo(x){ console.log(x) } function go(){ arr.map(echo); } 
 <button onclick="go()">Test</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM