Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array extension method gets iterated in for loop

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?

like image 825
Jacob Avatar asked Dec 28 '22 16:12

Jacob


2 Answers

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.

like image 70
SLaks Avatar answered Mar 31 '23 22:03

SLaks


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.

like image 29
Ilia Choly Avatar answered Apr 01 '23 00:04

Ilia Choly