为什么拼接方法有这种奇怪的行为? [英] Why does the splice method have this strange behavior?
问题描述
在我的应用程序需要从一个数组中删除的元素。不过,我是新来的JS。我在网上搜索,每一个博客文章在谈论拼接()方法。所以,我认为用它,但它有一个很奇怪的行为。
In my application I need to delete an element from an array. However I am new to JS. I searched the web and every blog post was talking about splice() method. So I considered to used it, but it has a very strange behavior.
在这里,我找到了帖子:
http://www.w3schools.com/jsref/jsref_splice.asp
http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/
Here the post I found : http://www.w3schools.com/jsref/jsref_splice.asp http://viralpatel.net/blogs/javascript-array-remove-element-js-array-delete-element/
下面是我的测试:
it("should delete all elements in array", function () {
var ary = new Array();
for (i = 0; i < 10; i++) {
ary[i] = Math.random();
}
expect(ary.length).toBe(10);
for (i = 0; i < 10; i++) {
ary.splice(i, 1);
}
expect(ary.length).toBe(0);
});
这里是测试结果:
And here is the result of the test:
Firefox 15.0.1 Linux: Run 7 tests (Passed: 6; Fails: 1; Errors 0) (44.00 ms)
should delete all elements in array failed (5.00 ms): Error: Expected 5 to be 0.
我用角JS。
非常感谢您的答复。这里是另一个试验,只是不通过:
Thanks very much for replies. Here is another test that just don't pass:
var ary = new Array();
ary = ['a', 'b', 'c', 'd'];
ary.splice(0, 1);
ary.splice(1, 1);
ary.splice(2, 1);
ary.splice(3, 1);
expect(ary.length).toBe(0);
Firefox 15.0.1 Linux: Run 7 tests (Passed: 6; Fails: 1; Errors 0) (49.00 ms)
Posting server policy.should delete all elements in array failed (5.00 ms): Error: Expected 2 to be 0.
作为@Matteo Tassinari认为这应该应该删除右边的所有元素?
as @Matteo Tassinari suggest this should one should delete all elements right ??
推荐答案
原因很简单:每一个新的拼接
您的阵列将变得更短:
The reason is simple: with each new splice
your array will become shorter:
var arr = [1, 2, 3];
arr.splice(0, 1);
console.log(arr[0]); // 2
console.log(arr[2]); // undefined
console.log(arr.length); // 2
在您的code的第二个循环拼接
将改变你的数组只有五次。但是,第六次(当 I
将等于5), arr.splice(5,1)
操作有效地导致无操作,因为你的阵列将是已经5个元素而已。
In the second loop of your code splice
will change your array only five times. But the sixth time (when i
will be equal to 5), arr.splice(5, 1)
operation will effectively result in no-op, as your array will be already of 5 elements only.
您可以修复它作为@MatteoTassinari答案,或者只是使用拼接(0,1)
(或只是移()
)代替拼接(I,1)
。
You can fix it as in @MatteoTassinari answer, or just use splice(0, 1)
(or just shift()
) instead of splice(i, 1)
.
这篇关于为什么拼接方法有这种奇怪的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!