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
  • 3,041
  • 6
  • 24
  • 46

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

P.S.
  • 15,970
  • 14
  • 62
  • 86
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
  • 19,201
  • 4
  • 67
  • 93
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,287
  • 1
  • 22
  • 30
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
  • 132,000
  • 20
  • 149
  • 151
  • 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