Array.prototype.splice的意外行为 [英] Unexpected behavior of Array.prototype.splice
问题描述
在实施内部 EventEmitter
的一个项目我工作,我遇到了一个奇怪的怪癖时使用 Array.prototype.splice
在为中...
循环。该功能不会成功地从数组中删除内环路的indeces:
VAR阵列= [1,2,3,4,5],指数;\r
\r
对于(数组索引){\r
如果(指数=== 2){\r
方法Array.splice(指数,1);\r
}\r
\r
的console.log(数组[指数]);\r
}\r
\r
的console.log(阵列);
\r
运行在谷歌Chrome浏览器版本43,此输出
1
2
3
4
五
[1,2,3,4,5]
当我期待像
1
2
4
五
未定义†
[1,2,4,5]
这设计还是错误是?我找不到任何记录引用此行为。
†可能的话,如果没有在实施为...的每次迭代期间计算长度
大问题。 :)
在Javascript中,数组是对象,这意味着数组的索引是对象键。而在Javascript中,对象键是字符串。
所以,你的条件指数=== 2
总是会是假的,因为2号是不一样的字符串'2'。
一个解决办法是继续使用的身份运营商(按最值得推荐的)和首页
比较字符串值2
指数==='2'
或者,或者,你可以使用等于运算符将强制转换的比较(虽然这将有可能让你陷入困境在某种程度上)...
指数== 2
但在你的情况下工作得很好。
While implementing an internal EventEmitter
for a project I was working on, I came across a strange quirk when using Array.prototype.splice
inside a for... in
loop. The function does not successfully remove the indeces from the array within the loop:
var array = [1, 2, 3, 4, 5], index;
for (index in array) {
if (index === 2) {
array.splice(index, 1);
}
console.log(array[index]);
}
console.log(array);
Running on Google Chrome version 43, this outputs
1
2
3
4
5
[1, 2, 3, 4, 5]
when I'm expecting something like
1
2
4
5
undefined†
[1, 2, 4, 5]
Is this by design or a bug? I cannot find any documented reference to this behavior.
† Possibly, if length is not calculated during each iteration of for... in
implementation
Great question. :)
In Javascript, Arrays are Objects, which means that Array indices are Object keys. And in Javascript, Object keys are strings.
So your condition index === 2
is always going to be false, because the number 2 is not the same as the string '2'.
One solution would be to continue to use the identity operator (recommended by most) and compare index
to the string value '2'
index === '2'
Or, alternatively, you can use the equality operator which will typecast the comparison (although this will likely get you into trouble at some point)...
index == 2
but works just fine in your case.
这篇关于Array.prototype.splice的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!