foreach - javascript iterate array - For-each over an array in JavaScript

javascript for loop / javascript / arrays / loops / iteration

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

I thought it was something like this:

forEach(instance in theArray)

Peter Mortensen



Answer #1

A forEach implementation (see in jsFiddle):

function forEach(list,callback) {
  var length = list.length;
  for (var n = 0; n < length; n++) {
    callback.call(list[n]);
  }
}

var myArray = ['hello','world'];

forEach(
  myArray,
  function(){
    alert(this); // do something
  }
);