adding numbers in for loop javascript
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/