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 = [];
$('#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
精彩评论