Skip to content Skip to sidebar Skip to footer

Stopping Enumeration In Javascript When Using Prototype

I'm currently trying to get my head around using prototype in JavaScript. To experiment with this, I've written a function that effectively works as allowing you to put a where cla

Solution 1:

The for...in construct enumerates all properties of an object (and those inherited down the prototype chain). When you use it with an array, it will iterate over all properties of Array.prototype, as well as the elements of the array.

Use a normal for loop to prevent this:

for(var x = 0; x < this.length; x++) {
    //Do stuff
}

Solution 2:

In general, using a for ... in loop to iterate through an array is bad practice.

However, a simple fix would be to use Object.hasOwnProperty:

for (var x in someArray) {
  if (someArray.hasOwnProperty(x)) {
    //...
  }
}

This is a more robust approach than your loop.

Solution 3:

In general, you should not mess with the prototypes of native Objects. This leads to problems - especially in combination with extern code/libraries.

Instead, you should make it a function that operates on an array parameter (for instance function arrayWhere(arr)).

If you want to stick to extending native prototypes, you should iterate over arrays with the forEach method (newer browsers, maybe add a fallback as described at the MDN), or the hasOwnProperty method of objects, as described in this example.

Post a Comment for "Stopping Enumeration In Javascript When Using Prototype"