javascript 如何在javascript中创建带有可变参数的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7362671/
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
how to create functions with variable arguments in javascript?
提问by McSas
I want to create a function in javascript with a variable amount of arguments. The next example is how I want to call this function:
我想用可变数量的参数在 javascript 中创建一个函数。下一个例子是我想如何调用这个函数:
myFunction(1,2);
myFunction(1,2,3);
myFunction(1,2,3,4);
myFunction(1,2,3,4,5);
myFunction(1,2,3,4,5,6);
Anyone knows how to define this function?
有谁知道如何定义这个函数?
回答by Alex K.
You can access the arguments by their ordinal position without the need to state them in the prototype as follows:
您可以按顺序访问参数,而无需在原型中声明它们,如下所示:
function myFunction() {
for (var i = 0; i < arguments.length; i++)
alert(arguments[i]);
}
myFunction(1, 2, "three");
>>1
>>2
>>three
Or if you really are passing in a set of semantically related numbers you could use an array;
或者,如果您确实要传入一组语义相关的数字,则可以使用数组;
function myFunction(arr) { ... }
result = myFunction([1,2,3]);
回答by optimistanoop
Latest update
最新更新
Rest parametersare supported in all new browsers. Check here for details
所有新浏览器都支持Rest 参数。 在这里查看详细信息
The rest parameter syntax allows us to represent an indefinite number of arguments as an array, which you can pass it to other functions too.
其余参数语法允许我们将无限数量的参数表示为一个数组,您也可以将其传递给其他函数。
function myFunction(...data){
console.log(...data);
myOtherFunction(...data);
}
myFunction(1,2,3); //logs 1,2,3
myFunction([1,2,3]); //logs [1,2,3]
回答by Jean-Charles
Use the 'arguments' variable like this :
像这样使用“参数”变量:
function myFunction() {
alert(arguments.length + ' arguments');
for( var i = 0; i < arguments.length; i++ ) {
alert(arguments[i]);
}
}
Call the methods as you did before
像以前一样调用方法
myFunction(1,2);
myFunction(1,2,3,4,5,6);
回答by Matthew Wilson
回答by Stephan
If an argument is not present, use the default. Like this...
如果参数不存在,则使用默认值。像这样...
function accident() {
//Mandatory Arguments
var driver = arguments[0];
var condition = arguments[1]
//Optional Arguments
var blame_on = (arguments[2]) ? arguments[2] : "Irresponsible tree" ;
}
accident("Me","Drunk");
回答by serv-inc
As an add-on: You can assign values to the unnamed function parameters, as in (german wiki)
作为附加组件:您可以为未命名的函数参数赋值,如(德语维基)
arguments[0] = 5;