Stan
Stan

Reputation: 26501

Add all elements in array

I have function that is getting the width of my images in list and I need to count them all together. When I do it in foreach it brings some weird number.

This function is getting width of every element, I really don't care about every element, just how much width they are taking together...

var listWidth = [];
$('#thumbContainer ul li').each(function(){
    listWidth.push($(this).width());
});

Upvotes: 1

Views: 9438

Answers (2)

NullVoxPopuli
NullVoxPopuli

Reputation: 65123

I like to use this:

Array.prototype.addAll = function() {
/** Adds all the elements in the
    specified arrays to this array. 
*/
    for (var a = 0;  a < arguments.length;  a++) {
        arr = arguments[a];
        for (var i = 0;  i < arr.length;  i++) {
            this.push(arr[i]);
        }
    }
}

Source

Upvotes: 2

user113716
user113716

Reputation: 322492

Not sure what you tried, but this should work:

var listWidth = 0;
$('#thumbContainer ul li').each(function(){
    listWidth += $(this).width();
});

alert( listWidth );

...or this:

var listWidth = 0;
$('#thumbContainer ul li').width(function(i,wid){ listWidth += wid; });

alert( listWidth );

Upvotes: 5

Related Questions