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
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().
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With