在 JavaScript 中将数组作为函数参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2856059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing an array as a function parameter in JavaScript
提问by Robert
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 ) {
// ...
}
Is there a better way of passing the contents of xinto call_me()?
有没有更好的方法来传递xinto的内容call_me()?
回答by KaptajnKold
const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);
See MDN docs for Function.prototype.apply().
参见 MDN 文档Function.prototype.apply()。
If the environment supports ECMAScript 6, you can use a spread argumentinstead:
如果环境支持 ECMAScript 6,则可以改用spread 参数:
call_me(...args);
回答by Karl Johan
Why don't you pass the entire array and process it as needed inside the function?
为什么不传递整个数组并根据需要在函数内部进行处理?
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}
回答by plexer
Assuming that call_me is a global function, so you don't expect this to be set.
假设 call_me 是一个全局函数,所以你不希望它被设置。
var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
回答by BoltKey
In ES6 standard there is a new spread operator...which does exactly that.
在 ES6 标准中,有一个新的扩展运算符...可以做到这一点。
call_me(...x)
It is supported by all major browsers except for IE.
除 IE 外,所有主流浏览器都支持它。
The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.
展开运算符可以做许多其他有用的事情,链接文档在展示这一点方面做得非常好。
回答by u2575951
As @KaptajnKold had answered
正如@KaptajnKold 所回答的那样
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
And you don't need to define every parameters for call_me function either.
You can just use arguments
而且您也不需要为 call_me 函数定义每个参数。你可以使用arguments
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
回答by ali.b.y
Note this
注意这个
function FollowMouse() {
for(var i=0; i< arguments.length; i++) {
arguments[i].style.top = event.clientY+"px";
arguments[i].style.left = event.clientX+"px";
}
};
//---------------------------
//----------------------------
html page
html页面
<body onmousemove="FollowMouse(d1,d2,d3)">
<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>
</body>
can call function with any Args
可以使用任何参数调用函数
<body onmousemove="FollowMouse(d1,d2)">
or
或者
<body onmousemove="FollowMouse(d1)">
回答by vsync
回答by Naba
While using spread operator we must note that it must be the last or only parameter passed. Else it will fail.
在使用扩展运算符时,我们必须注意它必须是最后一个或唯一传递的参数。否则会失败。
function callMe(...arr){ //valid arguments
alert(arr);
}
function callMe(name, ...arr){ //valid arguments
alert(arr);
}
function callMe(...arr, name){ //invalid arguments
alert(arr);
}
If you need to pass an array as the starting argument you can do:
如果您需要传递一个数组作为起始参数,您可以执行以下操作:
function callMe(arr, name){
let newArr = [...arr];
alert(newArr);
}
回答by rman
you can use spread operator in a more basic form
您可以以更基本的形式使用扩展运算符
[].concat(...array)
in the case of functions that return arrays but are expected to pass as arguments
对于返回数组但预期作为参数传递的函数
Example:
例子:
function expectArguments(...args){
return [].concat(...args);
}
JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))
回答by Humoyun Ahmad
The answer was already given, but I just want to give my piece of cake. What you want to achieve is called method borrowingin the context of JS, that when we take a method from an object and call it in the context of another object. It is quite common to take array methods and apply them to arguments. Let me give you an example.
答案已经给出,但我只想给我的小菜一碟。你想要实现的是method borrowing在 JS 的上下文中调用,即当我们从一个对象中获取一个方法并在另一个对象的上下文中调用它时。采用数组方法并将它们应用于参数是很常见的。让我给你举个例子。
So we have "super" hashing function which takes two numbers as an argument and returns "super safe" hashed string:
所以我们有“超级”散列函数,它将两个数字作为参数并返回“超级安全”散列字符串:
function hash() {
return arguments[0]+','+arguments[1];
}
hash(1,2); // "1,2" whoaa
So far so good, but we have little problem with the above approach, it is constrained, only works with two numbers, that is not dynamic, let's make it work with any number and plus you do not have to pass an array (you can if you still insist). Ok, Enough talk, Let's fight!
到目前为止一切顺利,但我们对上述方法没有什么问题,它是受约束的,只能处理两个数字,这不是动态的,让我们让它处理任何数字,而且您不必传递数组(您可以如果你仍然坚持)。好了,废话不多说,战斗吧!
The natural solution would be to use arr.joinmethod:
自然的解决方案是使用arr.join方法:
function hash() {
return arguments.join();
}
hash(1,2,4,..); // Error: arguments.join is not a function
Oh, man. Unfortunately, that won't work. Because we are calling hash(arguments) and arguments object is both iterable and array-like, but not a real array. How about the below approach?
天啊。不幸的是,这行不通。因为我们正在调用 hash(arguments) 和 arguments 对象既可迭代又类似于数组,但不是真正的数组。下面的方法怎么样?
function hash() {
return [].join.call(arguments);
}
hash(1,2,3,4); // "1,2,3,4" whoaa
The trick is called method borrowing.
诀窍被称为 method borrowing.
We borrow a joinmethod from a regular array [].join.And use [].join.callto run it in the context of arguments.
我们join从常规数组中借用了一个方法[].join.并使用[].join.call它在 的上下文中运行它arguments。
Why does it work?
为什么有效?
That's because the internal algorithm of the native method arr.join(glue)is very simple.
那是因为原生方法的内部算法arr.join(glue)非常简单。
Taken from the specification almost “as-is”:
几乎“按原样”取自规范:
Let glue be the first argument or, if no arguments, then a comma ",".
Let result be an empty string.
Append this[0] to result.
Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.
Return result.
So, technically it takes this and joins this[0], this[1] …etc together. It's intentionally written in a way that allows any array-like this (not a coincidence, many methods follow this practice). That's why it also works with this=arguments.
因此,从技术上讲,它需要将 this[0]、this[1] ...等连接在一起。它故意以允许任何类似数组的方式编写(并非巧合,许多方法都遵循这种做法)。这就是为什么它也适用于this=arguments.

