gpt4 book ai didi

javascript - 为什么拼接方法有这种奇怪的行为?

转载 作者:行者123 更新时间:2023-11-30 07:43:07 25 4
gpt4 key购买 nike

在我的应用程序中,我需要从数组中删除一个元素。但是我是 JS 的新手。我在网上搜索了一下,每篇博文都在谈论 splice() 方法。所以我考虑使用它,但它有一个非常奇怪的行为。

这是我找到的帖子: http://www.w3schools.com/jsref/jsref_splice.asphttp://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);

});

测试结果如下:

  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.

我使用 Angular JS。

非常感谢您的回复。这是另一个没有通过的测试:

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 建议的那样,应该删除所有元素吗??

最佳答案

原因很简单:每一个新的拼接你的数组都会变短:

var arr = [1, 2, 3];
arr.splice(0, 1);
console.log(arr[0]); // 2
console.log(arr[2]); // undefined
console.log(arr.length); // 2

在代码的第二个循环中,splice 只会改变数组五次。但是第六次(当 i 等于 5 时),arr.splice(5, 1) 操作将有效地导致空操作,因为您的数组将是已经只有 5 个元素。

您可以按照@MatteoTassinari 的回答修复它,或者只使用 splice(0, 1) (或只是 shift())而不是 splice(我, 1).

关于javascript - 为什么拼接方法有这种奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com