I am trying to write a cross browser foreach
method/function. It should be possible to either use the real, or a copy of the values or properties of the array or object to iterate over (just like the PHP foreach ($array as &$item)
).
Neither the forEach nor the map method is cross browser compatible, so I will be needing for loops.
This topic JavaScript for...in vs for warned me to not use for... in
to loop through arrays, but when I test with the following code:
var arr = [];
arr[3] = "foo";
arr[0] = "bar";
arr["baz"] = "baz";
for (var i in arr) {
alert(i);
}
I get the results 3, 0 and baz (which is correct). This also seems to work on indexed arrays (0, 1, 2). Yet Object.prototype.toString.call(arr) === "[object Array]"
returns true.
So what is the best cross browser approach to create a foreach method which will iterate over both array values and object properties, ideally offering the option to work with the actual values/properties of the array/object?