aurelien pirra aurelien pirra - 7 months ago 87
jQuery Question

how to get a total value of an variable in Jquery each

I try to get the total that is returned whith this each :

$.each(resStats,function(key, value){
var test = value.users_count_view;
console.log(test);
});


the
console.log
return 6 and 2. How i can have directly the result : 8

Answer Source

1st: Define total before/outside the loop .. If not it'll overwritten each time

2nd: Use += to add value to the total in the loop

3rd: You'll need to use parseInt() The parseInt() function parses a string and returns an integer.

4th: console.log the total outside the loop to give you the total value without console.log each time

var total = 0;
$.each(resStats,function(key, value){
   total += parseInt(value.users_count_view);           
});
console.log(total); 

The above code will output 8

If you use console.log(total); inside the loop

var total = 0;
$.each(resStats,function(key, value){
   total += parseInt(value.users_count_view);
   console.log(total);            
});

The above code will output 6 then 8

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download