Skip to main content
deleted 5 characters in body; deleted 19 characters in body
Source Link
Michael Robinson
  • 29.5k
  • 12
  • 107
  • 131

Javascript is treating your numbers as strings, and concatenating them together instead of adding them like you expect.

Use parseInt to convert them into integers before adding:

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

for(var i=1; i < nums.length; i++){
 
        var num += parseInt(nums[i], 10);
 
        alert(num);
}​

The second parameter tells parseInt to use base 10.

Javascript is treating your numbers as strings, and concatenating them together instead of adding them like you expect.

Use parseInt to convert them into integers before adding:

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

for(var i=1; i < nums.length; i++){
 
        var num += parseInt(nums[i], 10);
 
        alert(num);
}​

The second parameter tells parseInt to use base 10.

Javascript is treating your numbers as strings, and concatenating them together instead of adding them like you expect.

Use parseInt to convert them into integers before adding:

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

for(var i=1; i < nums.length; i++){
       num += parseInt(nums[i], 10);
       alert(num);
}​

The second parameter tells parseInt to use base 10.

Source Link
Michael Robinson
  • 29.5k
  • 12
  • 107
  • 131

Javascript is treating your numbers as strings, and concatenating them together instead of adding them like you expect.

Use parseInt to convert them into integers before adding:

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

var num = 0;

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

        var num += parseInt(nums[i], 10);

        alert(num);
}​

The second parameter tells parseInt to use base 10.