4

I have created a JavaScript extension for an array object as follows:

Array.prototype.where = function (lamda) {
var results = [];

for (var i in this) {
    if (lamda(this[i])) {
           results.push(this[i]);
        }
    }

    return results;
}

When I iterate through the array using a for loop like:

var myArray = [1,2,3,4];

for(var i in myArray){
   alert(myArray[i]);
}

...my extensions are enumerated as well.

Any ideas?

Chris Barlow
  • 3,274
  • 4
  • 31
  • 52
Jacob
  • 145
  • 7

3 Answers3

7

This behavior is by design.
for / in loops iterate over every property in an object, including those inherited from prototypes.

You can check if (myArray.hasOwnProperty(i)) to skip inherited properties.

However, you should use a regular for loop instead.
Javascript's for / in loop is not intended to loop over arrays.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks for your response. i'm still new to javascript and am used to using the enhanced for loops like in C#. I've changed my javascript to use a regular for loop and all is well. Thank you. – Jacob Aug 04 '11 at 13:23
3

That's javascript's normal functionality. the for .. in loop gets all of an object's keys because it is meant for looping over an object, not an array.

Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
0

If you want to add a non-enumerable property to Array, you can do it like this:

Object.defineProperty( Array.prototype, "where", {
    value: function where( i: number, j: number ): void {
        ...
    }
} );

see here: Change Array.prototype in node.js

graham
  • 70
  • 5