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.

2

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.