0

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.

Ashot Khachatryan
  • 2,156
  • 2
  • 14
  • 30
  • You shouldn't use for..in loops with arrays. Look at this SO post: http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea Also, read Mozilla's article and look at the section about arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in – Saad May 21 '15 at 08:45
  • can you show the full code (i.e. what you are passing to `calculateTime()`, also you need a `for` loop not a `for in` – atmd May 21 '15 at 08:45

3 Answers3

3

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);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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.

Siguza
  • 21,155
  • 6
  • 52
  • 89
0

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.

Bob
  • 523
  • 4
  • 11