开发者

how to create functions with variable arguments in javascript?

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:

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 fun开发者_Python百科ction?


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]);


Latest update

Rest parameters are supported in all new browsers. Check here for details

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]


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);


Just refer to the arguments array.

https://developer.mozilla.org/en/JavaScript/Reference/functions_and_function_scope/arguments


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");


As an add-on: You can assign values to the unnamed function parameters, as in (german wiki)

arguments[0] = 5;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜