Ashot Khachatryan
Ashot Khachatryan

Reputation: 2376

JavaScript for loop Index becomes arrayIndex

I have the following JavaScript code fragment

var ip = new Array();
// This array filled with values and passed to function
function calculateTime(ip) {
  for (i in ip) {
    window.alert(i);
    if (!i in myArray) {
      myArray[i] = 0;
    } else {
      myArray[i] += 1;
    }
  }
}

I expect i to be an index (0, 1, 2 ...) but sometimes window.alert prints "arrayIndex" and because of that my code doesn't work correctly. Can someone explain me the reason? I am new in JavaScript.

Upvotes: 0

Views: 41

Answers (3)

Quentin
Quentin

Reputation: 944016

for in will loop over all the enumerable properties of an object.

None of the properties that come with an array are enumerable in modern browsers, but any that are added (such as the normal array indexes or any custom named properties) will be.

Somewhere you have some code that is adding an arrayIndex property to your array and it is coming up when you loop over it.

var myArray = [];
myArray[0] = 1;
myArray[1] = 1;
myArray[2] = 1;
myArray.arrayIndex = 1;

for (prop in myArray) {
    console.log(prop);
}

If you only want to get numerical indexes, then use a standard for loop.

for (var i = 0 ; i < myArray.length ; i++) {
    console.log(i);
}

Upvotes: 3

Bob
Bob

Reputation: 523

Use either

for(var i=0; i<ip.length; i++){
    //your code
}

or

ip.forEach(function(val,i){
    // your code
});

The for(var x in y) loop works best for Object rather than Array. When you use it on arrays it will loop through all properties including named ones like length not just numerical indices.

Upvotes: 0

Siguza
Siguza

Reputation: 23870

For arrays, you should use a numeric variable rather than in:

for(var i = 0; i < ip.length; i++)

in is to iterate over the keys of an Object, but even there you have to take much care to filter out inherited properties.
Now, since arrays are objects too in JavaScript, you can assign them object properties:

ip["arrayIndex"] = 'some value';

Then "arrayIndex" will show up in a for...in iteration, whereas in a "normal" for loop, it won't.

Upvotes: 1

Related Questions