0

I have this function:

function getTotal () {
    var args = Array.prototype.slice.call(arguments);
    var total = 0;
    for (var i = 0; i < args.length; i++) {
        total += args[i];
    }

    return total;
}

Lets say that I have an array that is filled with numbers and I do not know the length of it:

var numArray = [ ..., ... ];

How can I call the function getTotal by passing in every element in the numArray as a parameter?

georgej
  • 2,771
  • 5
  • 22
  • 44

5 Answers5

5

In ES6 you can do this:

getTotal(...numArray);

It called Spread syntax. For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Commercial Suicide
  • 14,875
  • 14
  • 62
  • 80
4

You can call the function using Function.prototype.apply. It will pass the Array as arguments to your function.

function getTotal () {
    var args = Array.prototype.slice.call(arguments);
    var total = 0;
    for (var i = 0; i < args.length; i++) {
        total += args[i];
    }

    return total;
}

var numArray = [1,2,3,4];

console.log( getTotal.apply( null, numArray ) );

Keep in mind you have a typo in your for loop. Should be args.length, instead of arg.length.

drinchev
  • 18,618
  • 3
  • 63
  • 91
1

Please try this. Hope it helps

var sum = [1, 2, 3, 4, 5].reduce(add, 0);

function add(a, b) {
    return a + b;
}
0

Why not just do this:

function getTotal (args) {
    var total = 0;
    for (var i = 0; i < args.length; i++) {
        total += args[i];
    }

    return total;
}

var numArray = [1,2,3];
console.log(getTotal(numArray)); //6
Jerry Stratton
  • 3,057
  • 1
  • 21
  • 27
0

If you use the spread operator, you may also want to ES6ify your code:

function getTotal(...vals){
  return vals.reduce((a,b)=>a+b,0);
}

getTotal(...[1,2,4]);
Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
  • Spread is not an operator, see https://stackoverflow.com/q/37151966/. Note that `...vals` parameter at `function getTotal(...vals){}` is rest element, not spread element – guest271314 Aug 11 '17 at 15:06