javascript tutorial - [Solved-5 Solutions] For-each over an array in javascript - javascript - java script - javascript array



Problem

How can I loop through all the entries in an array using JavaScript?

Solution 1:

forEach(instance in theArray)

Solution 2:

TL;DR

Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.

Your best bets are usually

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • Your best bets are usually a for-of loop (ES2015+ only),Array#forEach (spec | MDN) (or its relatives some and such) (ES5+ only),a simple old-fashioned for loop,or for-in with safeguards.

Solution 3:

The standard way to iterate an array in JavaScript is a vanilla for -loop:

var length = arr.length,
    element = null;
for (var i = 0; i < length; i++) {
  element = arr[i];
  // Do something with element i.
}
click below button to copy the code. By JavaScript tutorial team

Solution 4:

$.each(yourArray, function(index, value) {
  // do your stuff here
});
click below button to copy the code. By JavaScript tutorial team

Solution 5:


for (var i = array.length; i--; ) {
     // process array[i]
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - For-each over an array in javascript