How can I loop through all the entries in an array using JavaScript?
I thought it was something like this:
forEach(instance in theArray)
Where theArray
is my array, but this seems to be incorrect.
How can I loop through all the entries in an array using JavaScript? I thought it was something like this:
Where |
||||
TL;DR
But there's lots more to explore, read on... JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-like, such as the I'll quickly note that you can use the ES2015 options now, even on ES5 engines, by transpiling ES2015 to ES5. Search for "ES2015 transpiling" / "ES6 transpiling" for more... Okay, let's look at our options: For Actual ArraysYou have three options in ECMAScript 5 ("ES5"), the version most broadly supported at the moment, and will soon have two more in ECMAScript 2015 ("ES2015", "ES6"), the latest version of JavaScript that vendors are working on supporting:
Details: 1. Use
|
|
I would also like to add that
.forEach cannot be broken efficiently. You have to throw an exception to perform the break.
– Pijusn
May 6 '13 at 20:12
|
||
|
@Pius: If you want to break the loop, you can use
some . (I would have preferred allowing breaking forEach as well, but they, um, didn't ask me. ;-) )
– T.J. Crowder
May 6 '13 at 21:17
|
||
|
@T.J.Crowder True, even though it looks more like a work-around as it's not its primary purpose.
– Pijusn
May 6 '13 at 21:23
|
||
|
Never call list.length in test expression if list wasn't changed.
– Alex Yaroshevich
Dec 15 '14 at 12:11
|
||
|
@user889030: You need a
, after k=0 , not a ; . Remember, programming is many things, one of which is close attention to detail... :-)
– T.J. Crowder
Apr 7 at 9:41
|
Edit: This answer is hopelessly out-of-date. For a more modern approach, look at the methods available on an array. Methods of interest might be:
The standard way to iterate an array in JavaScript is a vanilla
Note, however, that this approach is only good if you have a dense array, and each index is occupied by an element. If the array is sparse, then you can run into performance problems with this approach, since you will iterate over a lot of indices that do not really exist in the array. In this case, a In ECMAScript 5 there will be a forEach method on the array prototype, but it is not supported in legacy browsers. So to be able to use it consistently you must either have an environment that supports it (for example, Node.js for server side JavaScript), or use a "Polyfill". The Polyfill for this functionality is, however, trivial and since it makes the code easier to read, it is a good polyfill to include. |
|||||||||||||||||
|
If you’re using the jQuery library, you can use jQuery.each:
EDIT : As per question, user want code in javascript instead of jquery so the edit is
|
|||||||||||||||||||||
|
Loop backwardsI think the reverse for loop deserves a mention here:
Advantages:
Disadvantages:
Should I always use it?Some developers use the reverse for loop by default, unless there is a good reason to loop forwards. Although the performance gains are usually insignificant, it sort of screams:
However in practice that is not actually a reliable indication of intent, since it is indistinguishable from those occasions when you do care about the order, and really do need to loop in reverse. So in fact another construct would be needed to accurately express the "don't care" intent, something currently unavailable in most languages, including ECMAScript, but which could be called, for example, If order doesn't matter, and efficiency is a concern (in the innermost loop of a game or animation engine), then it may be acceptable to use the reverse for loop as your go-to pattern. Just remember that seeing a reverse for loop in existing code does not necessarily mean that the order irrelevant! It is better to use forEach()In general for higher level code where clarity and safety are greater concerns, I would recommend using
Then when you do see the reverse for loop in your code, that is a hint that it is reversed for a good reason (perhaps one of the reasons described above). And seeing a traditional forward for loop may indicate that shifting can take place. (If the discussion of intent makes no sense to you, then you and your code may benefit from watching Crockford's lecture on Programming Style & Your Brain.) How does it work?
You will notice that
TriviaSome people like to draw a little arrow in the reverse
Credits go to WYL for showing me the benefits and horrors of the reverse for loop. |
|||||||||||||
|
Some C-style languages use
There is a catch.
Additionally, ECMAScript 5 has added a
It's important to note that |
|||||||||
|
If you want to loop over an array, use the standard three-part
You can get some performance optimisations by caching |
|||||||||||||||||||||
|
A forEach implementation (see in jsFiddle):
|
|||||||||||||
|
If you don't mind emptying the array:
|
|||||
|
I know this is an old post, and there are so many great answers already. For a little more completeness I figured I'd throw in another one using AngularJS. Of course, this only applies if you're using Angular, obviously, nonetheless I'd like to put it anyway.
There are different ways to use the forEach loop of angular. The simplest and probably most used is
Another way that is useful for copying items from one array to another is
Though, you don't have to do that, you can simply do the following and it's equivalent to the previous example:
Now there are pros and cons of using the Pros
Consider the following 2 nested loops, which do exactly the same thing. Let's say that we have 2 arrays of objects and each object contains an array of results, each of which has a Value property that's a string (or whatever). And let's say we need to iterate over each of the results and if they're equal then perform some action:
Granted this is a very simple hypothetical example, but I've written triple embedded for loops using the second approach and it was very hard to read, and write for that matter. Cons
I'm sure there's various other pros and cons as well, and please feel free to add any that you see fit. I feel that, bottom line, if you need efficiency, stick with just the native |
|||
|
An easy solution now would be to use the underscore.js library. It's providing many useful tools, such as A CodePen example of how it works is:
See also
|
||||
|
Probably the
The method will call from
And if you want it to be a function, you can do this:
If you want to break, a little more logic:
Example:
It returns:
|
||||
|
There are three implementations of
|
|||||
|
There isn't any
However, note that there may be reasons to use an even simpler
|
||||
|
As of ES6:
Where The braces ( |
||||
|
This is an iterator for NON-sparse list where the index starts at 0, which is the typical scenario when dealing with document.getElementsByTagName or document.querySelectorAll)
Examples of usage: Example #1
Example #2
Each p tag gets Example #3
Every other p tag gets Example #4
And finally the first 20 blue p tags are changed to green Caution when using string as function: the function is created out-of-context and ought to be used only where you are certain of variable scoping. Otherwise, better to pass functions where scoping is more intuitive. |
||||
|
There's no inbuilt ability to break in
This works because |
||||
|
jQuery way using
|
|||||
|
I also would like to add this as a composition of a reverse loop and an answer above for someone that would like this syntax too.
Pros: The benefit for this: You have the reference already in the first like that won't need to be declared later with another line. It is handy when looping trough the object array. Cons: This will break whenever the reference is false - falsey (undefined, etc.). It can be used as an advantage though. However, it would make it a little bit harder to read. |
||||
|
ECMAScript5 (the current version on Javascript) to work with Arrays. forEach - Iterates through every item in the array and do whatever you need with each item.
In case , more interested on operation on array using some inbuilt feature. map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.
reduce - As the name says it reduces the array to a single value by calling the given function passing in the currenct element and the result of the previous execution.
every - Returns true or false if all the elements in the array pass the test in the callback function.
filter - Very similar to every except that filter return an array with the elements that return true to the given function.
Hope this will be useful. |
|||
|
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?
forEach
and not justfor
. as stated, in c# it was a bit different, and that confused me :) – Dante1986 Feb 17 '12 at 13:57i < len
andi++
can be done by the engine, rather than by the interpreter.) – joeytwiddle Sep 30 '16 at 3:24