1

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); 

    };
0

5 Answers 5

2

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

jsFiddle Demo

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

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

1

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; 
    // ...
});

http://jsfiddle.net/DGPST/9/

Comments

0

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.

jsFiddle Demo

Comments

0

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); 

(demo with tidyed-up code).

Comments

0

You need to reset sum before the loop and pass the value to the $(each) callback like so: http://jsfiddle.net/DGPST/17/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.