Is there a way to iterate through arrays in JavaScript like the while (list($key,$value) = each($arrayname)) on PHP?
TIA
Iterating through JS arrays
Moderator: General Moderators
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.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
this part:
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.
Code: Select all
var theArray = ['first', 'second', 'third'];
theArray.forEach(function(elt, index) {
// do something
});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.