开发者

Add all elements in array

开发者 https://www.devze.com 2023-03-17 11:06 出处:网络
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.

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 = [];
$('#thumbCon开发者_Go百科tainer ul li').each(function(){
    listWidth.push($(this).width());
});


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消