javascript tutorial - [Solved-5 Solutions] Loop through an array - javascript - java script - javascript array
Problem:
for loop to traverse objects in an array is possible ?
Solution 1:
Use a sequential for loop:
It shouldn't be used for array-like objects because:
- The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.
- Inherited properties are also enumerated.
- The second point is that it can give we a lot of problems, for example, if we 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 we use some library that relies heavily on native prototypes augmention (such as MooTools for example).
- The for-in statement as we said before is there to enumerate object properties, for example:
- In the above example the has Own Property method allows we to enumerate only own properties, that's it, only the properties that the object physically has, no inherited properties.
- We would recommend we to read the following article:
Solution 2:
We can use map
(also known as apply
in other languages like Python, and probably Haskell too)
The general syntax is:
func
should take one parameter.- The return value of
array.map
is another array, so we can use it like this:
- And now x is
[10,20,30,40]
. - We must clarify: This concept is from the functional paradigm.
- We don't have to write the function inline; one might do so as a first sketch, but we could then extract it into its own function.
which would be sort-of equivalent to:
except we don't get the new_list
.
Solution 3:
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.
Solution 4:
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
loop
logs: 'one','two','three'
Solution 5:
If we want a terse way to write a fast loop and we 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 unlike for(var i=0;i<myArray.length;++i)) while being fewer characters to type.
- There are even some times when we ought to iterate in reverse, such as when iterating over a live NodeList where we plan on removing items from the DOM during iteration.