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?
There are a couple of ways to do it in JavaScript. The first two examples are JavaScript samples. The third one makes use of a JavaScript library, that is, jQuery making use of the
.each()
function.In JavaScript, there are so many solutions to loop an array.
The code below are popular ones
Use a sequential
for
loop:@zipcodeman suggests the use of the
for...in
statement, but for iterating arraysfor-in
should be avoided, that statement is meant to enumerate object properties.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
Array.prototype
object to include a method there, that property will be also enumerated.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
for-in
statement as I said before is there to enumerate object properties, for example:In the above example the
hasOwnProperty
method allows you to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.I would recommend you to read the following article:
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
for
loop:Modern browsers all support iterator methods
forEach
,map
,reduce
,filter
and a host of other methods on the Array prototype.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,
for (var i = 0; i < array.length; i++) if (i in array)
orarray.forEach
withes5shim
should be used.Short answer: yes. You can do with this:
In a browser console, you can see something like "element1", "element2", etc., printed.