如何从forEach循环中的数组中删除元素?

IT技术 javascript foreach
2021-01-22 15:04:47

我试图在forEach循环中删除数组中的一个元素,但是我在使用标准解决方案时遇到了问题。

这就是我目前正在尝试的:

review.forEach(function(p){
   if(p === '\u2022 \u2022 \u2022'){
      console.log('YippeeeE!!!!!!!!!!!!!!!!')
      review.splice(p, 1);
   }
});

我知道它正在进入,if因为我YippeeeeeE!!!!!!!!!!!!!在控制台中看到

我的问题:我知道我的 for 循环和 if 逻辑是合理的,但是我从数组中删除当前元素的尝试失败了。

更新:

尝试了 Xotic750 的答案,该元素仍然没有被删除:

这是我的代码中的函数:

review.forEach(function (item, index, object) {
    if (item === '\u2022 \u2022 \u2022') {
       console.log('YippeeeE!!!!!!!!!!!!!!!!')
       object.splice(index, 1);
    }
    console.log('[' + item + ']');
});

这是数组仍未删除的输出:

[Scott McNeil]
[reviewed 4 months ago]
[ Mitsubishi is AMAZING!!!]
YippeeeE!!!!!!!!!!!!!!!!
[• • •]

很明显,它按照指示进入 if 语句,但同样明显的是 [• • •] 仍然存在。

6个回答

看起来您正在尝试这样做?

使用Array.prototype.splice迭代和改变数组

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
<pre id="out"></pre>

对于没有 2 个与相邻数组项相同的值的简单情况,这很好用,否则你会遇到这个问题。

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
<pre id="out"></pre>

那么在迭代和变异数组时,我们可以对这个问题做些什么呢?那么通常的解决方案是反向工作。使用ES3但你可以使用,如果首选糖

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a' ,'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.length - 1;

while (index >= 0) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }

  index -= 1;
}

log(review);
<pre id="out"></pre>

好的,但是您想使用 ES5 迭代方法。好吧,选项是使用Array.prototype.filter但这不会改变原始数组而是创建一个新数组,因此虽然您可以获得正确答案,但它并不是您所指定的。

我们也可以使用 ES5 Array.prototype.reduceRight,不是因为它的减少属性而是它的迭代属性,即反向迭代。

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.reduceRight(function(acc, item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
}, []);

log(review);
<pre id="out"></pre>

或者我们可以像这样使用 ES5 Array.protoype.indexOf

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.indexOf('a');

while (index !== -1) {
  review.splice(index, 1);
  index = review.indexOf('a');
}

log(review);
<pre id="out"></pre>

但是你特别想使用 ES5 Array.prototype.forEach,那我们怎么办?那么我们需要使用Array.prototype.slice来制作数组的浅拷贝和Array.prototype.reverse以便我们可以反向工作以改变原始数组。

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.slice().reverse().forEach(function(item, index, object) {
  if (item === 'a') {
    review.splice(object.length - 1 - index, 1);
  }
});

log(review);
<pre id="out"></pre>

最后,ES6 为我们提供了一些进一步的选择,我们不需要制作浅拷贝和反转它们。值得注意的是,我们可以使用Generators 和 Iterators然而,目前支持率相当低。

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

function* reverseKeys(arr) {
  var key = arr.length - 1;

  while (key >= 0) {
    yield key;
    key -= 1;
  }
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

for (var index of reverseKeys(review)) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }
}

log(review);
<pre id="out"></pre>

以上所有内容需要注意的是,如果您从数组中剥离NaN,那么与 equals 进行比较将不起作用,因为在 Javascript 中NaN === NaN是错误的。但是我们将在解决方案中忽略它,因为它是另一个未指定的边缘情况。

所以我们有了它,一个更完整的答案,解决方案仍然存在边缘情况。第一个代码示例仍然是正确的,但如前所述,它并非没有问题。

注意 - 这个答案是错误的!foreach 按索引遍历数组。一旦您在迭代以下项目的索引时删除元素,就会发生变化。在这个例子中,一旦你删除了第一个 'a',索引号 1 现在变成了 'c'。因此,第一个 'b' 甚至不被评估。既然你没有尝试删除它,它只是碰巧没问题,但那不是方法。您应该遍历数组的反向副本,然后删除原始数组中的项目。
2021-03-30 15:04:47
谢谢回答。我尝试使用您的解决方案,但它仍然没有从数组中删除元素。我会在问题中提供详细信息。
2021-03-31 15:04:47
小心,如果要删除两个连续的元素,这会中断: var review = ['a', 'a', 'c', 'b', 'a']; 将产生 ['a', 'c', 'b']
2021-04-03 15:04:47
@Xotic750 - 原始答案(现在是第一个代码片段)是错误的,因为 forEach 不会遍历数组中的所有元素,正如我在之前的评论中所解释的那样。我知道问题是如何删除 forEach 循环中的元素,但简单的答案是您不这样做。由于很多人都在阅读这些答案,并且多次盲目复制答案(尤其是已接受的答案),因此注意代码中的缺陷很重要。我认为反向while循环是最简单、最有效、最易读的解决方案,应该是公认的答案
2021-04-05 15:04:47
放在console.log(review);之后forEach,就像我的例子一样。
2021-04-08 15:04:47

使用Array.prototype.filter代替forEach

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);

尽管Xotic750 的回答提供了几个优点和可能的解决方案,但有时简单更好

您知道正在迭代的数组在迭代本身中发生了变化(即删除项目 => 索引更改),因此最简单的逻辑是在老式for(à la C语言)中倒退

let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i] === 'a') {
    arr.splice(i, 1);
  }
}

document.body.append(arr.join());

如果你真的考虑一下,aforEach只是一个for循环的语法糖......所以如果它对你没有帮助,请停止反对它。

您也可以使用 indexOf 来代替执行此操作

var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);

我知道您想使用条件从数组中删除并拥有另一个从数组中删除项目的数组。是对的?

这个怎么样?

var review = ['a', 'b', 'c', 'ab', 'bc'];
var filtered = [];
for(var i=0; i < review.length;) {
  if(review[i].charAt(0) == 'a') {
    filtered.push(review.splice(i,1)[0]);
  }else{
    i++;
  }
}

console.log("review", review);
console.log("filtered", filtered);

希望这有助于...

顺便说一下,我将“for-loop”与“forEach”进行了比较。

如果在字符串包含 'f' 的情况下删除,则结果不同。

var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];
var filtered = [];
for(var i=0; i < review.length;) {
  if( review[i].includes('f')) {
    filtered.push(review.splice(i,1)[0]);
  }else {
    i++;
  }
}
console.log("review", review);
console.log("filtered", filtered);
/**
 * review [  "concat",  "copyWithin",  "entries",  "every",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"] 
 */

console.log("========================================================");
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];
filtered = [];

review.forEach(function(item,i, object) {
  if( item.includes('f')) {
    filtered.push(object.splice(i,1)[0]);
  }
});

console.log("-----------------------------------------");
console.log("review", review);
console.log("filtered", filtered);

/**
 * review [  "concat",  "copyWithin",  "entries",  "every",  "filter",  "findIndex",  "flatten",  "includes",  "join",  "keys",  "map",  "pop",  "push",  "reduce",  "reduceRight",  "reverse",  "slice",  "some",  "sort",  "splice",  "toLocaleString",  "toSource",  "toString",  "values"]
 */

并且每次迭代删除,结果也不同。

var review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];
var filtered = [];
for(var i=0; i < review.length;) {
  filtered.push(review.splice(i,1)[0]);
}
console.log("review", review);
console.log("filtered", filtered);
console.log("========================================================");
review = ["of", "concat", "copyWithin", "entries", "every", "fill", "filter", "find", "findIndex", "flatMap", "flatten", "forEach", "includes", "indexOf", "join", "keys", "lastIndexOf", "map", "pop", "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toSource", "toString", "unshift", "values"];
filtered = [];

review.forEach(function(item,i, object) {
  filtered.push(object.splice(i,1)[0]);
});

console.log("-----------------------------------------");
console.log("review", review);
console.log("filtered", filtered);