【发布时间】:2014-04-18 17:26:54
【问题描述】:
我想在数组上添加一个“插入”方法。 所以我这样做:
> Array.prototype.insert = function(index, element){
this.splice(index, 0, element);
};
它的工作原理:
> a = [1,2,3]
[1, 2, 3]
> a.insert(0, 4)
undefined
> a
[4, 1, 2, 3]
但是有一个不受欢迎的副作用:
> 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);
}
这种行为不是故意的,会破坏我使用的其他库。 有什么优雅的解决方案吗?
【问题讨论】:
-
这就是为什么你永远不应该在数组上使用
for..in。 -
您仍然可以使用
for循环的其他构造:for ( var i = 0; i < a.length; i++ ) { console.log(a[i]); } -
同意!但是现在我们倾向于重用很多其他人的代码,并且很难确保所有库都遵循这一规则。
-
事实上,这是反对做你想做的事情的一个很好的论据。不要修改您不拥有的对象。 nczonline.net/blog/2010/03/02/…
标签: javascript prototype for-in-loop