0

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, 20 and 30 again?

kamaci
  • 72,915
  • 69
  • 228
  • 366

3 Answers3

2
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]
}
szanata
  • 2,402
  • 17
  • 17
  • i agree and changed the example – szanata Mar 02 '11 at 12:33
  • 1
    Could you remove the second form (for...in)? It’s a bad example; for..in should be used to loop over the keys of an object, not to loop through the elements of an array. See http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays – Martijn Mar 02 '11 at 12:34
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);
});
RoToRa
  • 37,635
  • 12
  • 69
  • 105
1

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/

Torbjörn Hansson
  • 18,354
  • 5
  • 33
  • 42
  • @Raynos In my opinion it gets cleaner and since we're using jQuery there is no problem (see tags). But of course it's the same as as a for loop. It's a question of taste I guess. – Torbjörn Hansson Mar 02 '11 at 12:46
  • I just see little reason to abstract away a `for` loop on an `Array`. Admittedly it's a valid style choice. It just feels very unnecessary. Especially when he cares about order, you shouldn't use an orderless each loop. – Raynos Mar 02 '11 at 13:02
  • @Raynos - you are missing the point of down voting. According to its page, down voting is used `Whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect, vote it down!` You already admitted it is a style issue. Calm down with the down votes. – Jeff Mar 02 '11 at 21:00
  • @Jeff I did realise I was being harsh afterwards but the vote is locked. – Raynos Mar 02 '11 at 21:06