Monday, June 3, 2024
168
rated 0 times [  169] [ 1]  / answers: 1 / hits: 20401  / 13 Years ago, fri, september 9, 2011, 12:00:00

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 function?


More From » variadic-functions

 Answers
19

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

[#90184] Thursday, September 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katieh

Total Points: 692
Total Questions: 104
Total Answers: 104

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
katieh questions
;