javascript 在javascript函数参数列表中传递可变数量的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19629011/
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 Variable Number of arguments in javascript function argument-list
提问by Navyah
Can I pass a variable number of arguments into a Javascript function? I have little knowledge in JS. I want to implement something like the following:
我可以将可变数量的参数传递给 Javascript 函数吗?我对JS知之甚少。我想实现如下内容:
function CalculateAB3(data, val1, val2, ...)
{
...
}
回答by aga
You can pass multiple parameters in your function and access them via argumentsvariable. Here is an example of function which returns the sum of all parameters you passed in it
您可以在函数中传递多个参数并通过参数变量访问它们。这是一个函数示例,它返回您传入的所有参数的总和
var sum = function () {
var res = 0;
for (var i = 0; i < arguments.length; i++) {
res += parseInt(arguments[i]);
}
return res;
}
You can call it as follows:
您可以按如下方式调用它:
sum(1, 2, 3); // returns 6
回答by Satpal
Simple answer to your question, surely you can
简单回答你的问题,你肯定可以
But personally I would like to pass a object rather than n
numbers of parameters
但我个人想传递一个对象而不是n
参数数量
Example:
例子:
function CalculateAB3(obj)
{
var var1= obj.var1 || 0; //if obj.var1 is null, 0 will be set to var1
//rest of parameters
}
Here ||
is logical operator for more info visit http://codepb.com/null-coalescing-operator-in-javascript/
这||
是更多信息的逻辑运算符,请访问http://codepb.com/null-coalescing-operator-in-javascript/
A Is there a "null coalescing" operator in JavaScript?is a good read
回答by uzumaxy
Yes, you can make it. Use variable arguments
like there:
是的,你可以做到。使用变量arguments
像那里:
function test() {
for(var i=0; i<arguments.length; i++) {
console.log(arguments[i])
}
}