Add methods to Array.prototype, without the side e

2019-07-09 09:22发布

I'd like to add an "insert" method on Arrays. So I'm doing it like this:

> Array.prototype.insert = function(index, element){
    this.splice(index, 0, element);
};

And it works:

> a = [1,2,3]
[1, 2, 3]
> a.insert(0, 4)
undefined
> a
[4, 1, 2, 3]

But there's an undesired side effect:

> for (i in a){console.log(i)}
0
1
2
3
insert

> for (i in a){console.log(a[i])}
4
1
2
3
function (index, element){
    this.splice(index, 0, element);
}

This behavior is not intended and breaks other libraries that I use. Is there any elegant solution for this?

2条回答
贼婆χ
2楼-- · 2019-07-09 09:46

Object.defineProperty works, but it won't be supported in older browsers. (compatibility table)

Object.defineProperty(Array.prototype, 'insert', {
  enumerable: false,
  value: function(index, element){
    this.splice(index, 0, element);
  }
});

Demonstration

查看更多
Viruses.
3楼-- · 2019-07-09 09:55

In this loop inherited properties (insert method) are not displayed.

  for (i in a){if (a.hasOwnProperty(i)) {console.log(i)}}

So, every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

This method compatible with all browsers

查看更多
登录 后发表回答