1

I extended Array to support indexOf in IE using this JavaScript function from Mozilla MDC.

Unfortunately, when using for...in syntax to iterate over the Array, the loop stops on indexOf instead of just numerical indexes.

Can I keep indexOf out of for...in syntax in Internet Explorer (it does in Chrome)? What makes the Array.length property and other Array functions so special that the for...in loop skips over them?

I know that switching to standard for syntax is a solution, but I would prefer a for...in fix.

6
  • 6
    the solution is not to use for..in for iterating over the array. the reason length and other properties don't show up is because of the internal DontEnum attribute in ES3. ES5 standardizes this behavior though, so you can make your properties non-enumerable as well. Commented Feb 4, 2011 at 5:55
  • I can't control what other people do with this JS file. They might decide to use for...in on Array while this is included. Commented Feb 4, 2011 at 5:57
  • 1
    See stackoverflow.com/questions/2636453/… Commented Feb 4, 2011 at 5:58
  • @weberwithoneb then I'm afraid you will have to make it a stand alone function. At least until ES5 is widely available. Commented Feb 4, 2011 at 5:59
  • Thanks @Anurag as well for the clarification. Commented Feb 4, 2011 at 6:15

1 Answer 1

1

Aside from avoiding the for...in notation for arrays, try to apply defensive programming:
When using the for (... in ...) syntax in ES3 (current browsers), it's always recommended that you filter it:

var member;
for (member in someObject) {
  if (someObject.hasOwnProperty(member)) {
    someObject[member]; // do whatever you want with it
  }
}

Other code could also enrich some object prototype.

Sign up to request clarification or add additional context in comments.

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.