删除“;这个“;数组的索引不起作用

Removing "this" index of array not working

本文关键字:索引 不起作用 这个 删除 数组      更新时间:2023-09-26

这是我的代码:

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数字]",为什么删除了错误的索引?

x.splice(x.length, 1)删除一个从x.length开始的元素,该元素在数组的边界之外;使用x.splice(x.length - 1, 1)或仅使用x.pop()

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

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

这实际上会将timeoutID推送到数组中。随后是一个额外的推送x.push('k'),因此当超时解决时,k元素实际上会被删除。

x.length将在超时功能内部发生更改。如果要使用要添加的元素的索引,请将x.length存储为更高范围中的变量。

http://jsfiddle.net/rrw3s/