首页 > 解决方案 > 当我在这个数组上使用 forEach 时,如何从数组中删除一个项目?

问题描述

我有一个包含函数/对象的数组。此对象具有测试自身的功能,如果它们失败,它们会从数组中删除。如果我在这个数组上运行一个 forEach 并运行这个 testfunction 并且一个对象从数组中删除,那么 forEach 循环会跳过一个对象。

解决这个问题的好方法是什么?

这里举个例子。运行示例,您将看到tests.push(new Test(2));在 forEach 循环中跳过了 2ed 对象。

//creating a test array
var tests = [];
tests.push(new Test(1));
tests.push(new Test(2));
tests.push(new Test(3));
tests.push(new Test(4));

function Test(n) {
  this.n = n;

  this.testme = function() {
    if(this.n < 3) {
	  tests.splice(tests.indexOf(this), 1); //remove me from the array tests please!
	  console.log(this.n, "I got removed!");
    } else {
      console.log(this.n, "I can stay!");
    }
  } 
}


console.log("tests length: ", tests.length);

tests.forEach(function(t) {
  t.testme();
});

console.log("tests length: ", tests.length); //output should now be 2 

标签: javascriptarrays

解决方案


为什么不使用内置filter功能?

tests = tests.filter(t => t.testMe());

推荐阅读