问题
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?
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/22387766/add-methods-to-array-prototype-without-the-side-effects