for loop to traverse objects in an array is possible ?
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:
The general syntax is:
funcshould take one parameter.
- The return value of
array.mapis another array, so we can use it like this:
- And now x is
- 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
It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.
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
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.