Reputation: 13
I am attempting to loop through my array elements, find the sum of them and update a div with the value.
For some reason, my each() loop doesn't work as expected. For example, when I enter 12, 3 times, the answer should be 36, but I get 72.
Any suggestions, thanks!
View full code here: http://jsfiddle.net/lakesmaa/DGPST/3/
$.each(array, function() {
sum += parseInt(this);
});
$('.total').html(sum);
};
Upvotes: 1
Views: 115
Reputation: 213223
On every click of button, you are adding the item to the array:
array.push(newItem);
then iterating over the array, and adding each item to sum.
So, on 1st click:
array = [12], sum = 12
on 2nd click:
array = [12, 12], sum = (12 + 12 + 12) = 36
on 3rd click:
array = [12, 12, 12], sum = 36 + 12 + 12 + 12 = 72
Either you reset the sum
inside your function to 0
:
$('#button').click(function() {
var sum = 0; // reset
Or, add the item directly, without iterating over the array:
array.push(newItem);
sum += parseInt(newItem);
// Remove the for each loop iterating over the array to accumulate sum
Upvotes: 2
Reputation: 16184
You need to reset sum
before the loop and pass the value to the $(each)
callback like so:
http://jsfiddle.net/DGPST/17/
Upvotes: 0
Reputation: 664297
You want to reset the sum to zero each time before summing up the array values. Currently you have just one global variable to which you add all values when clicking the button.
var sum = 0;
$.each(array, function() {
sum += parseInt(this);
});
$('.total').html(sum);
Upvotes: 0
Reputation: 71908
You never reset the sum
inside your click handler, so on every click you start from where you left.
You need:
// ...
$('#button').click(function() {
var sum = 0;
// ...
});
Upvotes: 1
Reputation: 66961
That is because you are using this
within your $.each()
, which is expecting & trying to parse a jQuery wrapped element.
this
in your instance is actually String {0: "1", 1: "2"}
(console.log it and you'll see)
Instead use the item (2nd parameters) of the .each()
callback function.
$.each(array, function(index, item) {
sum += parseInt(item);
});
This will intern give you, 36 when 12 is entered 3 times, as intended.
Upvotes: 0