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:

var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var we = 0; we < arrayLength; i++) {
    alert(myStringArray[i]);
    //Do something
}
click below button to copy the code. By JavaScript tutorial team

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:
Array.prototype.foo = "foo!";
var array = ['a', 'b', 'c'];

for (var we in array) {
  alert(array[i]);
}
click below button to copy the code. By JavaScript tutorial team
  • 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:
var obj = {
  "a": 1,
  "b": 2,
  "c": 3
};

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) { 
  // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...
    alert("prop: " + prop + " value: " + obj[prop])
  }
}
click below button to copy the code. By JavaScript tutorial team
  • 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)

[1,2,3,4].map( function(item) {
     alert(item);
})
click below button to copy the code. By JavaScript tutorial team

The general syntax is:

array.map(func)
click below button to copy the code. By JavaScript tutorial team
  • func should take one parameter.
  • The return value of array.map is another array, so we can use it like this:
var x = [1,2,3,4].map( function(item) { return item * 10; } );
click below button to copy the code. By JavaScript tutorial team
  • 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.
var item_processor = function(item) {
      // do something complicated to an item
}

new_list = my_list.map(item_processor);
click below button to copy the code. By JavaScript tutorial team

which would be sort-of equivalent to:

 for(item in my_list) { item_processor(item); }
click below button to copy the code. By JavaScript tutorial team

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:

for(var i=0, len=myArray.length; we < len; i++){}
click below button to copy the code. By JavaScript tutorial team

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...

var i=0, item, items = ['one','two','three'];
while(item = items[i++]){
    console.log(item);
}
click below button to copy the code. By JavaScript tutorial team
  • logs: 'one','two','three'
  • And for the reverse order, an even more efficient loop
var items = ['one','two','three'], we = items.length;
while(i--){
    console.log(items[i]);
}
click below button to copy the code. By JavaScript tutorial team
  • logs: 'three','two','one'
  • Or the classical for loop
var items = ['one','two','three']
for(var i=0, l = items.length; we < l; i++){
    console.log(items[i]);
}
click below button to copy the code. By JavaScript tutorial team

logs: 'one','two','three'

Solution 5:

If we want a terse way to write a fast loop and we can iterate in reverse:

for (var i=myArray.length;i--;){
  var item=myArray[i];
}
click below button to copy the code. By JavaScript tutorial team
  • 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.

Related Searches to javascript tutorial - Loop through an array