我正在尝试编辑数组并删除不满足特定条件的元素。如果我将 reverse for loop
与 .splice(index,n)
结合使用,代码就可以正常工作。我坚持使用 ES6 for...of
循环实现相同的功能
let array=[1,2,3];
//reverse for loop
for(var i=array.length - 1; i>=0; i--) {
if(array[i]>=2) {
/*Collect element before deleting it.*/
array.splice(i,1);
}
}
console.log(array);
// returns [1]
用于..of
let array=[1,2,3];
for(let entry of array) {
if(entry>=2) {
let index = array.indexOf(entry);
/*The array is being re-indexed when I apply
.splice() - the loop will skip over an index
when one element of array is removed*/
array.splice(index, 1);
}
}
console.log(array);
//returns [1,3]
有没有一种方法可以使用 for...of
循环来实现此功能,还是我必须坚持使用 reverse for loop
更新
我需要将不符合 filter()
或 reverse for loop
函数删除的元素的条目收集到辅助数组。
最佳答案
你不能合理地为此使用for-of
。如果您在迭代期间删除“当前”条目,您将跳过下一个条目,因为指定数组迭代器的方式(它们使用条目的索引)。你可以通过这个人为的例子看到这一点:
const array = [1, 2, 3];
for (const entry of array) {
console.log(entry);
if (entry === 2) {
array.splice(1, 1);
}
}
console.log(array);
请注意条目 3
没有循环迭代。
我建议要么坚持使用反向 for
循环,要么使用 filter
生成一个仅包含您要保留的条目的新数组。
使用过滤器
:
let array = [1, 2, 3];
array = array.filter(entry => entry < 2);
console.log(array);
我在上面说“合理”是因为,当然,总有办法。您可以遍历数组的副本并在其外部维护 index
:
const array = [1, 2, 3];
let index = 0;
for (const entry of [...array]) {
if (entry >= 2) {
array.splice(index, 1);
} else {
++index;
}
}
console.log(array);
与其他选择相比,这似乎不合理,当然除非有限制迫使您那样做。 :-)
关于javascript - 使用 for...of 循环删除数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753537/