简体   繁体   中英

javascript storing array values

Im trying to get the total combined value of a set of numbers. Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong. check the jsfiddle too see example

http://jsfiddle.net/Wd78j/

var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
    x.push(parseInt(z[i]));
}
console.log(x);

var total = 0;
$.each(x,function() {
    total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.

var x = [];

$('.impressions').each( function( ) {
    var z = $(this).text();
    x.push(parseInt(z, 10));
})

Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.

text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.

You want to loop through each impressions element, and keep a running sum going. Something like this should work

var sum = 0;
$('.impressions').each(function(){
   sum = sum + (+$(this).text());
});

Updated Fiddle


Or to keep your original structure (don't forget the radix parameter to parseInt):

var z = $('.impressions');
var x = [];
z.each(function(){
    x.push(parseInt($(this).text(), 10));
});
console.log(x);

var total = 0;
$.each(x,function() {
    total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

Updated fiddle

You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :

var x     = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
    total = 0,
    n     = x.length;

while(n--) total += x[n] || 0;

$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM