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?