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?

3 Answers 3

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]
}
Sign up to request clarification or add additional context in comments.

2 Comments

i agree and changed the example
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 stackoverflow.com/questions/500504/…
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);
});

1 Comment

Can you give an example usage(for ex. alerting items at list?)
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/

4 Comments

@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.
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 - 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 I did realise I was being harsh afterwards but the vote is locked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.