最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add all elements in array - Stack Overflow

programmeradmin1浏览0评论

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

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());
});
Share Improve this question asked Jul 4, 2011 at 23:10 StanStan 26.5k55 gold badges168 silver badges247 bronze badges 2
  • What, exactly is your problem? How is the number "weird"? Also, why can't you accumulate in the body of the loop? Finally, if you want to build an array, use map rather than each. – Marcin Commented Jul 4, 2011 at 23:17
  • One think to watch out for is that if you have: <ul><li>Text</li></ul>, and do the width of the li tag, you will get the width to the edge of the containing block, not just the width of the text. The li would have to be inline to get just the text width. – jfriend00 Commented Jul 4, 2011 at 23:57
Add a ment  | 

2 Answers 2

Reset to default 5

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)

  1. 暂无评论