Search code examples
javascriptarrayssumtypeof

JavaScript how to evaluate type of variable and return sum of an array


So I am trying to write a function that evaluates an array and only output the sum of all number variables from the array. For example, if I enter the array [1,2,3,"chunky bacon", 5, false], it will only adds up 1,2,3,and 5, thus return 11. Here is what I wrote:

var sum = function(num) {
    var total = 0;
    for (var i = 0; i < num.length; i++) {
        if (typeof i == "number") {
            total += num[i];
        };
    };
    console.log(total);
}

However when I tested it in my console with [1,2,3,"chunky bacon", 5, false], it will return

6chunky bacon5false

So my question is 1)How would I make the loop don't stop when it runs into a none number element, so in the above example it will continue to add 6 with 5? 2)How would I make it stop printing the none number elements? I don't know why it prints it out since I only said console.log(total).

Thanks for your help!


Solution

  • (typeof i == "number") is always a number because "i" is your loop counter. You should use

    if (typeof num[i] == "number")
    

    (snippet not tested)