0

Possible Duplicate:
Is it possible to send a variable number of arguments to a JavaScript function?

How would I pass a different number of variables to a function every time I call it?

For example if I have function add(), would I be able to pass 5 arguments to it and use arguments.length in loop to do the sum?

Community
  • 1
  • 1
MAS
  • 45
  • 7
  • What exactly is your question? How to pass a variable number of arguments to a function? Or accessing a variable number of arguments from within the function? I'm a a bit confused. – Felix Kling Oct 12 '12 at 05:29
  • What about passing as an array? http://cs-netlab-01.lynchburg.edu/courses/WebProg/javascript/JSParamPassing.htm – arjuncc Oct 12 '12 at 05:29
  • It seems you have not really tried anything on your own before posting this question. – Kaustubh Karkare Oct 12 '12 at 05:41

2 Answers2

2
function add() {
    var sum = 0;
    for (var i=0; i<arguments.length; i++)
        sum += arguments[i];
    return sum;
}

Get it?

MiniGod
  • 3,683
  • 1
  • 26
  • 27
0

You need to pass an array to the function. Each time you call the function, regardless of what values/how many values you have in the array, the function can access these values. The values in the array will be available to the function to do the summation. For example (assuming that the array is not a global variable):

function add(array) {
    var sum = 0;
    for (var i=0; i<array.length; i++)
        sum += array[i];
    return sum;
}
whistler
  • 876
  • 2
  • 15
  • 31