如何在不中断 For 循环的情况下遍历数组并删除项目
前言
- 在本教程转自国外网站 网站地址
- 在笔者看来这是一篇难得好文章故翻译转载。
- 您将找到一种优雅的方式来遍历数组并在不中断for循环的情况下删除项目。
我们知道splice()方法可用于包括删除一个元素、添加、替换等。但是,当您运行时,该数组正在重新编制索引splice(),这意味着您将在删除一个索引时跳过该索引。
首先,让我们好好了解splice()方法的工作原理。
The splice() Method
splice()方法可以通过删除或替换现有元素或添加新元素来修改数组的内容。虽然它就地更改了原始数组,但它仍会返回已删除项目的列表。如果没有删除的数组,则返回一个空数组。
js代码片断
。
const anyFish= ["angel", "drum", "mandarin", "sturgeon"];
/*Remove 1 element at index 2*/
const removed = anyFish.splice(2, 1);
/* anyFish is ["angel", "drum", "sturgeon"] */
/* removed is ["mandarin"] */
现在开始我们的例子,看看这个问题。如果我们运行代码片段并查看结果,我们将看到 3 仍在数组中,这正是我们上面提到的问题:
下面展示一些 内联代码片
。
let elements = [1, 3, 3, 5, 3, 1, 4];
let removeEl = 3;
let index = elements.indexOf(removeEl);
// we continue this till we find the element in the array
// indexOf will return the first index of the element in the array; -1 if not found
while (index !== -1) {
elements.splice(index, 1);
// we get the new index after splice()
index = elements.indexOf(removeEl);
}
console.log(elements);
- 代码运行结果如下:
> Array [ 1, 5, 1, 4 ]
这将防止重新索引影响迭代中的下一个项目,因为索引只影响从当前点到数组末尾的项目。在迭代中,下一项低于当前点。
或者我们可以开始反向循环:
下面展示一些 内联代码片
。
let elements = [1, 3, 8, 5, 16, 1, 4];
// here, we start iterating from the last element to the first one (reverse)
for (i = elements.length - 1; i >= 0; --i) {
if (elements[i] % 2 === 0) {
elements.splice(i, 1); // Remove even numbers
}
}
console.log(elements);
- 代码运行结果如下:
> Array [ 1, 3, 5, 1 ]
让我们更优雅地完成它!
下面展示一些 内联代码片
。
let elements = [1, 3, 3, 5, 3, 1, 4];
// filter方法中的元素将表示每次迭代中的每个数组元素
// 在这里,如果元素不等于3,它将保留在结果数组中
const result = elements.filter((element) => element != 3)
console.log(result)
- 代码运行结果如下:
> Array [ 1, 5, 1, 4 ]