gpt4 book ai didi

javascript - 删除数组的 "this"索引不起作用

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

这是我的代码:

var x = [{letter: "a"}, {letter: "b"}, {letter: "c"}]

x.push({
timer: setTimeout(function() {x.splice(x.length - 1, 1)}, 3000),
letter: "j",
})

x.push({letter: "k"})

setTimeout(function() {alert(x)}, 4000)

我的主要问题是:为什么代码在应该警告“a,b,c,k”时却警告“a,b,c,[A number]”,为什么它删除了错误的索引?

最佳答案

x.splice(x.length, 1) 删除从 x.length 开始的一个元素,该元素超出了数组的范围;使用 x.splice(x.length - 1, 1) 或仅使用 x.pop()。

如果想法是让对象从数组中删除自身,请在添加它之前存储长度并使用它:

<b>var removeIndex = x.length;</b>

x.push({
timer: setTimeout(function() { x.splice(<b>removeIndex</b>, 1); }, 3000),
letter: "j"<s>,</s>
});

关于javascript - 删除数组的 "this"索引不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512955/

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