将未知数量的参数传递给 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4116608/
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
Pass unknown number of arguments into javascript function
提问by ajsie
Is there a way to pass an unknown number of arguments like:
有没有办法传递未知数量的参数,例如:
var print_names = function(names) {
foreach(name in names) console.log(name); // something like this
}
print_names('foo', 'bar', 'baz');
Also, how do I get the number of arguments passed in?
另外,如何获取传入的参数数量?
回答by ShZ
ES3 (or ES5 or oldschool Javascript)
ES3(或 ES5 或 oldschool Javascript)
You can access the arguments passed to any javascript function via the magic arguments
object, which behaves similarly to an array. Using arguments
your function would look like
您可以通过魔术arguments
对象访问传递给任何 javascript 函数的参数,其行为类似于数组。使用arguments
您的功能看起来像
var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}
It's important to note that arguments
is notan array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
这是需要注意的重要的arguments
是不是一个数组。MDC 有一些很好的文档:https: //developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
If you want to turn arguments
into an array so that you can do things like .slice()
, .push()
etc, use something like this:
如果你想arguments
变成一个数组,以便你可以做类似的事情.slice()
,.push()
等等,使用这样的东西:
var args = Array.prototype.slice.call(arguments);
ES6 / Typescript
ES6 / 打字稿
There's a better way! The new rest parametersfeature has your back:
有更好的方法!新的休息参数功能支持您:
var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}
回答by RationalDev likes GoFundMonica
ES6/ES2015
ES6/ES2015
Take advantage of the rest parameter syntax.
利用其余参数语法。
function printNames(...names) {
console.log(`number of arguments: ${names.length}`);
for (var name of names) {
console.log(name);
}
}
printNames('foo', 'bar', 'baz');
There are three main differences between rest parameters and the arguments object:
其余参数和参数对象之间存在三个主要区别:
- rest parameters are only the ones that haven't been given a separate name, while the arguments object contains all arguments passed to the function;
- the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
- the arguments object has additional functionality specific to itself (like the callee property).
- 其余参数只是那些没有被赋予单独名称的参数,而参数对象包含传递给函数的所有参数;
- arguments 对象不是真正的数组,而其余参数是 Array 实例,这意味着可以直接对其应用 sort、map、forEach 或 pop 等方法;
- arguments 对象具有特定于自身的附加功能(如被调用者属性)。
回答by public override
var
print_names = function() {
console.log.apply( this, arguments );
};
print_names( 1, 2, 3, 4 );
回答by Gabi Purcaru
function print_args() {
for(var i=0; i<arguments.length; i++)
console.log(arguments[i])
}
回答by Jacob Relkin
There is a hidden object passed to every function in JavaScript called arguments
.
有一个隐藏对象传递给 JavaScript 中的每个函数,称为arguments
.
You would just use arguments.length
to get the amount of arguments passed to the function.
您只需使用arguments.length
来获取传递给函数的参数数量。
To iterate through the arguments, you would use a loop:
要遍历参数,您将使用循环:
for(var i = arguments.length; i--) {
var arg = arguments[i];
}
Note that arguments
isn't a real array, so if you needed it as an array you would convert it like this:
请注意,这arguments
不是一个真正的数组,因此如果您需要将它作为数组,您可以像这样转换它:
var args = Array.prototype.slice.call(arguments);
回答by meder omuraliev
arguments.length
. you can use a for loop on it.
arguments.length
. 您可以在其上使用 for 循环。
(function () {
for (var a = [], i = arguments.length; i--;) {
a.push(arguments[i]);
};
return a;
})(1, 2, 3, 4, 5, 6, 7, 8)
回答by Santiago Posada
Much better now for ES6
ES6 现在好多了
function Example() {
return {
arguments: (...args) =>{
args.map(a => console.log());
}
}
}
var exmpl = new Example();
exmpl.arguments(1, 2, 3, 'a', 'b', 'c');
I hope this helps
我希望这有帮助
回答by Kurtis Streutker
Rest parameters in ES6
ES6 中的其余参数
const example = (...args) => {
for (arg in args) {
console.log(arg);
}
}
Note: you can pass regular parameters in before the rest params
注意:您可以在其余参数之前传递常规参数
const example = (arg1, ...args) => {
console.log(arg1);
for (arg in args) {
console.log(arg);
}
}
回答by mabulu
You can create a function using the spread/rest operator and from there on, you achieved your goal. Please take a look at the chunk below.
您可以使用 spread/rest 运算符创建一个函数,然后您就实现了目标。请看下面的块。
const print_names = (...args) => args.forEach(x => console.log(x));
回答by Lajos Arpad
You can use the spread/rest operator to collect your parameters into an array and then the length
of the array will be the number of parameters you passed:
您可以使用 spread/rest 运算符将您的参数收集到一个数组中,然后length
该数组的数量将是您传递的参数数量:
function foo(...names) {
console.log(names);
return names;
}
console.log(foo(1, 2, 3, 4).length);
Using BabelJSI converted the function to oldschool JS:
使用BabelJS我将函数转换为 oldschool JS:
"use strict";
function foo() {
for (var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++) {
names[_key] = arguments[_key];
}
console.log(names);
return names;
}