Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

In Java you can use a for loop to traverse objects in an array as follows:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray)
{
    // Do something
}

Can you do the same in JavaScript?

share|improve this question
3  
Ok, so I'm a bit confused, it's ok to use the enhanced for loop when you are accessing the objects? And use a sequential one for filling one? Is this correct? – Mark Szymanski Jun 10 '10 at 0:15
21  
no, it's really simple, array objects have numeric indexes, so you want to iterate over those indexes in the numeric order, a sequential loop ensures that, the enhanced for-in loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended... – CMS Jun 10 '10 at 0:38
1  
related - stackoverflow.com/questions/5349425/… – jondavidjohn Nov 1 '11 at 17:53
    
related - stackoverflow.com/q/6208964/31671 – alex Dec 18 '15 at 10:09
1  
jsben.ch/#/Q9oD5 <= Here a benchmark of a bunch of solutions for looping through arrays – EscapeNetscape Nov 3 at 19:45

32 Answers 32

It is better to use a sequential for loop:

for (var i = 0; i < myStringArray.length; i++) {
    // Do something
}
share|improve this answer

each loop of jQuery will be the Good Option as ,it's an Array

var myStringArray = ["Hello", "World"];
$.each(myStringArray,function(e){ console.log(myStringArray[e]) });
share|improve this answer

protected by Josh Crozier Mar 17 '14 at 2:31

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.