Javascript - custom object prototype method turns to index in array loop

There is something strange here. I have defined my own prototype method for object

called getSize

:

if (!Object.prototype.getSize) {
    Object.prototype.getSize = function() {
        var size = 0, key;
        for (key in this) {
            if (this.hasOwnProperty(key)) size++;
        }
        return size;
    };
}

      

It gives you the size of the object. Pretty simple, right? Here's where I got confused:

var l = ["foo", "bar"]
for (var i in l) {
    console.log(i);
}

      

:

0
1
getSize

      

Why getSize

is there

edit I know that arrays in javascript are objects too. My question is why the method turns into an index and not remains a method. It doesn't make any sense to me ...

+3


source to share


2 answers


Since it getSize

is an enumerable property, you can define it as non-enumerable:

Object.defineProperty(Object.prototype, 'getSize', {
  enumerable: false,
  value: function() {
    var size = 0, key;
    for (key in this) {
      if (this.hasOwnProperty(key)) size++;
    }
    return size;
  }
});

      



But you can also do:

Object.keys(object).length;

      

+4


source


Because it ["foo", "bar"]

is an object in JavaScript. Try running typeof ["foo", "bar"]

in console. He will give you back "object"

. This way you have extended the array methods as well. Once you have done that, you will need to check hasOwnProperty

in all iterations for..in

.



This happens with all global objects in JavaScript.

+3


source







All Articles