co*********@gmail.com wrote:
Is there a similar function in JS as the PHP foreach() loop?
I have created an object in JS:
var ibm = new Object();
ibm['0'] = 240;
ibm['1'] = 241;
ibm['2'] = 242;
ibm['3'] = 243;
Looks more like you want an array e.g.
var ibm = new Array();
imb[0] = 240;
ibm[1] = 241;
ibm[2] = 242;
ibm[3] = 243;
or shorter
var ibm = [ 240, 241, 242, 243 ];
If you use an array then stick with
for (var i = 0, l = ibm.length; i < l; i++) {
// use i and/or ibm[i] here
}
If you really want an object then for..in allows you to enumerate the
enumerable properties of the object e.g.
var ibm = new Object();
ibm['0'] = 240;
ibm['1'] = 241;
ibm['2'] = 242;
ibm['3'] = 243;
for (var key in ibm) {
// use key and/or imb[key] here
}
JavaScript 1.6 (only supported in Mozilla 1.8 respectively Firefox 1.5
currently) also has for each..in to enumerate the property values of
enumerable properties e.g.
for each (var value in ibm) {
alert(value);
}
Take note that both for..in and for each..in will enumerate properties
that are 'inherited', e.g. if you have
Object.prototype.god = 'Kibo';
var ibm = new Object();
ibm['0'] = 240;
for each (var value in ibm) {
alert(value);
}
then two values are enumerated.
--
Martin Honnen
http://JavaScript.FAQTs.com/