Page 1 of 1

Iterating through JS arrays

Posted: Tue Sep 20, 2005 1:33 pm
by pilau
Is there a way to iterate through arrays in JavaScript like the while (list($key,$value) = each($arrayname)) on PHP?
TIA

Posted: Tue Sep 20, 2005 2:11 pm
by Weirdan
http://developer.mozilla.org/en/docs/Co ... ay:forEach

Code: Select all

// emulation for IE and whatnot
if(!Array.prototype.forEach) {
  Array.prototype.forEach = function(callback, thisPtr) {
      for(var i=0, l=this.length; i<l; i++) {
          if(thisPtr) {
             callback.call(thisPtr, this[i], i, this);
          } else {
             callback(this[i], i, this);
          }
      }
  }
}

var theArray = ['first', 'second', 'third'];
theArray.forEach(function(elt, index) {
// do something
});

Posted: Tue Sep 20, 2005 2:14 pm
by pilau
Uh, could you... please explain your code? 8O

Posted: Tue Sep 20, 2005 2:22 pm
by John Cartwright
Read the link he gave you.. explains it well :?

Posted: Tue Sep 20, 2005 2:27 pm
by Weirdan
this part:

Code: Select all

var theArray = ['first', 'second', 'third'];
theArray.forEach(function(elt, index) {
// do something
});
uses Array.forEach method (documented at the link at the top of my previous post) to iterate over theArray
It's similar to array_walk in PHP, but syntactically somewhat resembles php's foreach() construct.

Unfortunately, IE does not support modern JavaScript. Their javascript implementation (called JScript) is, I believe, between js v1.3 and js v1.4 in terms of supported functionality.
Thus the first part ( if(!Array.prototype.forEach) ), used to provide ie's array implementation with forEach method.

Posted: Tue Sep 20, 2005 2:41 pm
by pilau
Jcart wrote:Read the link he gave you.. explains it well :?
Missed the link :o