javascript - 在遍历数组时从数组中删除项目是否会破坏循环,我该怎么办?

标签 javascript

我正在像这样循环遍历一个数组。

onScreenData.getTasks().array.forEach(function (task, taski, array) {
    if(task.checked){
        myTasks.addTask(task, state.name)
        onScreenData.removeTask(taski);
    }
})

onScreenData.removeTask() 包含 tasks.array.splice(index, 1);。 Tasks.array 与循环遍历的数组相同。当 tasks.array.splice(index, 1); 运行时,循环立即停止。对此可以做些什么?

最佳答案

根据 ECMA Script 5.1 标准规范 Array.prototype.forEach ,

The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callback will be the value at the time forEach visits them; elements that are deleted after the call to forEach begins and before being visited are not visited.

为了更好地理解这一点,请检查以下代码

var a = [1, 2, 3, 4];

a.forEach(function(currentItem, idx, array) {
    console.log(a.length, currentItem, idx, array);
    a.splice(idx, 1);
});

console.log(a);

它输出,

4 1 0 [ 1, 2, 3, 4 ]
3 3 1 [ 2, 3, 4 ]
[ 2, 4 ]

在第一次迭代中,a.length4,当前项为1,索引为0。这很好。我们在第一次迭代中删除索引 0 处的元素。

在第二次迭代中,由于删除了第一个元素,数组的长度缩小为 3,2 成为第一个元素,当前索引为 1。现在,索引 1 对应的项目是 3。因此,在本次迭代中将其删除。

现在,数组的长度为2,当前索引变为2。因为,我们无法访问索引 2 处的元素,所以当数组本身的大小为 2 时,JavaScript 会跳出循环。

因此,实际上我们已经跳过了被删除元素旁边的元素。

这就是为什么我们不应该在迭代数组时改变它。

这里最好的选择是使用,Array.prototype.filter , 像这样

onScreenData.array = onScreenData.getTasks().array.filter(function (task) {
    if(task.checked) {
        myTasks.addTask(task, state.name)
        return false;
    }
    return true;
});

关于javascript - 在遍历数组时从数组中删除项目是否会破坏循环,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22457651/

相关文章:

javascript - React Javascript 中高阶函数中函数中的两个箭头是什么

javascript - Vue JS - 动态地将类添加到一个元素,然后将类删除到 sibling

javascript - 模板字符串上的 netbeans javascript 错误(反引号)

javascript - 过滤重复键

Javascript 显示/隐藏正确的 div

javascript - 使用拦截器延迟所有请求

javascript - 如何在 WordPress 中链接脚本

javascript - 使用 Vimeo API 3 限制返回的数据

javascript - 试图刷新特定的 Canvas 元素

javascript - Tailwindcss 不适用于 NextJS 12。实验性功能