In Java you can use a for()
loop to go through objects in an array like so:
String[] myStringArray = {"Hello","World"};
for(String s : myStringArray)
{
//Do something
}
Can you do the same in JavaScript?
In Java you can use a
Can you do the same in JavaScript? |
||||
Use a sequential
@zipcodeman suggests the use of the It shouldn't be used for array-like objects because:
The second point is that it can give you a lot of problems, for example, if you extend the For example:
The above code will alert, "a", "b", "c" and "foo!". That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example). The
In the above example the I would recommend you to read the following article: |
|||||||||||||||||||||
|
You can use
The general syntax is:
The return value of
And now x is EDIT:I must clarify: this concept is from the functional paradigm. You don't have to write the function inline; one might do so as a first sketch, but you could then extract it into its own function.
which would be sort-of equivalent to:
except you don't get the |
|||||||||||||||||||||
|
To directly answer the question: usually not. JavaScript only has that capability if you're lucky enough to be in control of the JavaScript interpreter being used (usually not the case if it's browser-side code), and that implementation includes the
Or better yet, since Harmony also provides block-scoped variables via
Most JavaScript programmers are working in an environment that's not there yet, however. If you can assume the interpreter is compliant with version 5 of the specification (which means, for browser code, no versions of Internet Explorer before 9), then you can use the
If you want something that works in all versions of JavaScript, then you have to use an explicit counting loop. The safest version, which handles sparse arrays properly, is something like this:
Assigning the length value to the local variable (as opposed to including the full You will often see the length caching done in the loop initialization clause, like this:
The |
|||||||||||||||||||||
|
In JavaScript it's not advisable to loop through an Array with a for-in loop, but it's better using a for loop such as:
It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject. |
|||||||||||||||||||||
|
Opera, Safari, Firefox and Chrome now all share a set of enhanced Array methods for optimizing many common loops. You may not need all of them, but they can be very useful, or would be if every browser supported them. The mozilla labs published the algorithms they and webkit both use, so that you can add them yourself. filter returns an array of items that satisfy some condition or test. every returns true if every array member passes the test. some returns true if any pass the test. forEach runs a function on each array member and doesn't return anything. map is like forEach, but it returns an array of the results of the operation for each element. These methods all take a function for their first argument, and have an optional second argument, which is an object whose scope you want to impose on the array members as they loop through the function. Ignore it until you need it. indexOf and lastIndexOf find the appropriate position of the first or last element that matches its argument exactly.
|
|||||
|
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
logs: 'one','two','three' Reference: http://www.sitepoint.com/google-closure-how-not-to-write-javascript/ |
|||||||||||||||||
|
for (var s of myStringArray) {(Directly answering your question: now you can!) Most other answers are right, but they do not mention (as of this writing) that ECMA Script 6 is bringing a new mechanism for doing iteration, the This new syntax is the most elegant way to iterate an array in javascript (as long you don't need the iteration index), but it is not yet widely supported by the browsers. It currently works with Firefox 13+, Chrome 37+ and it does not work with other browsers (see browser compatibility below). It also works on Node (I tested it on version 0.12.0). Iterating an array
Iterating an array of objects
You could also iterate custom types, by defining an
Compatibility table: http://kangax.github.io/es5-compat-table/es6/#For..of loops Spec: http://wiki.ecmascript.org/doku.php?id=harmony:iterators } |
||||
|
I would thoroughly recommend making use of the underscore.js library. It provides you with various functions that you can use to iterate over arrays/collections. For instance:
|
|||||||||
|
There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.
Or if you really want to get the id and have a really classical
Modern browsers all support iterator methods |
|||||||||||||||||||||
|
If you're using the jQuery library, consider using http://api.jquery.com/jQuery.each/ From the documentation: jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated. |
|||||||||
|
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 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. |
|||||||||||||||||
|
I did not yet see this variation, which I personally like the best: Given an array:
You can loop over it without ever accessing the length property:
See this JsFiddle demonstrating that: http://jsfiddle.net/prvzk/ This only works for arrays that are not sparse. Meaning that there actually is a value at each index in the array. However, I found that in practice I hardly ever use sparse arrays in Javascript... In such cases it's usually a lot easier to use an object as a map/hashtable. If you do have a sparse array, and want to loop over 0 .. length-1, you need the for (var i=0; i<someArray.length; ++i) construct, but you still need an if inside the loop to check whether the element at the current index is actually defined. Also, as CMS mentions in a comment below, you can only use this on arrays that don't contain any falsish values. The array of strings from the example works, but if you have empty strings, or numbers that are 0 or NaN, etc. the loop will break off prematurely. Again in practice this is hardly ever a problem for me, but it is something to keep in mind, which makes this a loop to think about before you use it... That may disqualify it for some people :) What I like about this loop is:
The reason this works is that the array specification mandates that when you read an item from an index >= the array's length, it will return undefined. When you write to such a location it will actually update the length. For me, this construct most closely emulates the Java 5 syntax that I love:
... with the added benefit of also knowing about the current index inside the loop |
|||||||||
|
There are various way to loop through array in JavaScript. Generic loop:
ES5's forEach:
jQuery.each:
Have a look this for detailed information or you can also check MDN for looping through an array in JavaScript & using jQuery check jQuery for each. |
|||||
|
There's a method to iterate over only own object properties, not including prototype's ones:
but it still will iterate over custom-defined properties. In javascript any custom property could be assigned to any object including array. If one wants to iterate over sparsed array, |
|||||||||
|
The most elegant and fast way
http://jsperf.com/native-loop-performance/8 Edited (because I was wrong)Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time. Preparation:
Tests:
|
|||||||||||||||||||||
|
The optimized approach is to cache the length of array and using single var pattern initializing all variables with single var keyword.
If order of iteration does not matter than you should try reversed loop, it is fastest as it reduce overhead condition testing and decrement is in one statement:
or better and cleaner to use while loop:
|
||||
|
For example, I used in a Firefox console:
|
|||
|
It's not 100% identical, but similar:
|
|||||
|
|
||||
|
Well, how about this:
|
|||||||||||||
|
A lot cleaner... |
|||||
|
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
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