Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding numbers in for loop javascript

Tags:

javascript

I need to sum all my numbers from a for loop with javascript

var nums = ['100','300','400','60','40'];

for(var i=1; i < nums.length; i++){

        var num = nums[i] + nums[i];

        alert(num);
}​

can someone help http://jsfiddle.net/GYpd2/1/

the outcome i am looking for is 900

like image 769
user1503606 Avatar asked Feb 15 '26 06:02

user1503606


2 Answers

var nums = ['100','300','400','60','40'];
var sum = 0;

for(var i=0; i < nums.length; i++){

    sum += parseInt(nums[i]);

}

alert(sum);

Tested: http://jsfiddle.net/GYpd2/6/ (thanks to user1503606)

If nums contains numbers only there is no need for parseInt().

like image 54
Besnik Avatar answered Feb 17 '26 20:02

Besnik


Prime example for ES5's Array.prototype.reduce method. Like:

var nums  = ['100','300','400','60','40'];

var total = nums.reduce(function(a,b) {
    return (+a)+(+b);
});

Demo: http://jsfiddle.net/FwfmE/

like image 33
jAndy Avatar answered Feb 17 '26 20:02

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!