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?
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?
If you want a terse way to write a fast loop and you can iterate in reverse:
This has the benefit of caching the length (similar to
for (var i=0, len=myArray.length; i<len; ++i)
and unlikefor (var i=0; i<myArray.length; ++i)
) while being fewer characters to type.There are even some times when you ought to iterate in reverse, such as when iterating over a live NodeList where you plan on removing items from the DOM during iteration.
If you're using the jQuery library, consider using http://api.jquery.com/jQuery.each/
From the documentation:
Array loop:
Object loop:
Sure it's inefficient and many despise it, but it's one of the closest to the mentioned:
Use the while loop...
logs: 'one','two','three'
And for the reverse order, an even more efficient loop
logs: 'three','two','one'
Or the classical
for
looplogs: 'one','two','three'
Reference: http://www.sitepoint.com/google-closure-how-not-to-write-javascript/
If you want to use jQuery, it has a nice example in its documentation: