开发者

Iterating Over An Array in JavaScript

I have an array and filled its values like that:

$('#list input:checked').each(function() {
  deleteRecordIdsStr.push($(this).attr('name'));
});

I use that for my array:

deleteRecordIdsStr = deleteRecordIdsStr.join("-");

So I have an array like that. Let's accept that I pushed 10, 20, 30 to it at first and after that I made join.

How can I iterate over that array and get 10, 2开发者_JS百科0 and 30 again?


var ids = deleteRecordIdsStr.split("-");

split is a String method that creates an array.

and the iteration will be:

for (var i = 0, l = ids.length; i <l; i++){

  //something with ids[i]
}


The "standard" method is to use a forloop:

for (var i = 0, len = deleteRecordIdsStr.length; i < len; i++) {
  alert(deleteRecordIdsStr[i]);
}

But jQuery also provides an each method for arrays (and array-like objects):

$.each(deleteRecordIdsStr, function(item, index) {
   alert(item);
});


You can use the jQuery each function to easy iterate through them.

$.each(deleteRecordIdsStr.split('-'), function() {
     // this = 10, 20, 30 etc.
});

http://api.jquery.com/jQuery.each/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜