Caution when using for in iterator method with Javascript Arrays

Jump to: navigation, search

The "for in" iterator method in Javascript is intended for Objects. It appears to work fine on Arrays but if you extend the Array using .prototype, then the iterator will also iterate over the new properties and methods. This may be surprising since the "for in" iterator does not iterate over the built in Array methods and properties such as push(), pop(), join(), .length, etc. Also the "for in" iterator does not use the "length" property of the array. For example it fails if you attempt to initialize values in an array with a predefined length. See below. Example: myArray = newArray(10); myArray.length; // this returns 10; for (var index in myArray) { myArray[index] = 0; // this NEVER executes even though .length is 10. } Recommend you use a standard for loop to iterate over an Array. It will also give you flexibility to extend the Array object with custom methods using .prototype. for (var index = 0; index < myArray.length; ++index) { myArray[index]=0; // this does execute as expected }

See also

Use your Android as a Chamberlain garage door opener remote

Personal tools
Namespaces
Variants
Views
Actions
Navigation