This has bothered me for a while, see my jsfiddle: http://jsfiddle.net/DHR8Q/, which contains the following javascript code:
var id = "11111;22222;33333";
id = id.split(";");
alert(typeof id);
for (var i in id){
alert(id[i]);
}
When I split the variable id by the character “;”, then I use the for loop, I would assume that i == 0,1,2 because the string id was split into 3 parts, but this is not what happens. In reality i == 0,1,2,3,4.... Why does JavaScript do this?
This is because
for... initerates over all properties of an object (including those from theprototype).When you
for... inover an array, you get the array elements, as well as thelengthproperty, and any properties ofArray.prototype.You can fix this by using
hasOwnProperty:Though, I suggest not using
for... infor arrays, useforEach:Or a good ol’ for loop:
EDIT
The
forEachfunction is not available as a built-in on back-level browsers, so you can do this: