Iterating through JS arrays

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
pilau
Forum Regular
Posts: 594
Joined: Sat Jul 09, 2005 10:22 am
Location: Israel

Iterating through JS arrays

Post by pilau »

Is there a way to iterate through arrays in JavaScript like the while (list($key,$value) = each($arrayname)) on PHP?
TIA
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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
});
Last edited by Weirdan on Tue Sep 20, 2005 2:17 pm, edited 1 time in total.
pilau
Forum Regular
Posts: 594
Joined: Sat Jul 09, 2005 10:22 am
Location: Israel

Post by pilau »

Uh, could you... please explain your code? 8O
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Read the link he gave you.. explains it well :?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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.
pilau
Forum Regular
Posts: 594
Joined: Sat Jul 09, 2005 10:22 am
Location: Israel

Post by pilau »

Jcart wrote:Read the link he gave you.. explains it well :?
Missed the link :o
Post Reply