Skip to content Skip to sidebar Skip to footer

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: deleteRec

Solution 1:

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]
}

Solution 2:

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

Solution 3:

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/


Post a Comment for "Iterating Over An Array In JavaScript"