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?

5
  • This looks like a homework. Commented Aug 11, 2017 at 14:45
  • >by passing in every element in the numArray as a parameter? why would you do that when you can just pass the array? Commented Aug 11, 2017 at 14:46
  • @TimothyGroote this is not the actual function that I have, just a simplified version of it to focus on this single concept Commented Aug 11, 2017 at 14:48
  • @serdar.sanri its not homework lol Commented Aug 11, 2017 at 14:48
  • Possible duplicate of Converting an array to a function arguments list Commented Aug 11, 2017 at 14:51

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, sorry, i'll update the answer with EN version =)
This syntax KICKS ASS, ty for mentioning it instead standard apply pattern
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.

Comments

1

Please try this. Hope it helps

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

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

Comments

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

1 Comment

Spread is not an operator, see stackoverflow.com/q/37151966. Note that ...vals parameter at function getTotal(...vals){} is rest element, not spread element
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.