开发者

Javascript array extension method gets iterated in for loop

开发者 https://www.devze.com 2023-03-25 01:19 出处:网络
I have created a JavaScript ext开发者_如何学编程ension for an array object as follows: Array.prototype.where = function (lamda) {

I have created a JavaScript ext开发者_如何学编程ension 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?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号