在数组上使用forEach时,如何从数组中删除项目?

时间:2019-07-12 17:50:32

标签: javascript arrays

我有一个包含函数/对象的数组。该对象具有自我测试的功能,如果失败,则将其从阵列中删除。如果我在此数组上运行一个forEach并运行此测试函数,并且从该数组中删除了一个对象,则forEach循环将跳过一个对象。

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

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

//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 

2 个答案:

答案 0 :(得分:3)

为什么不使用内置的filter函数?

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

答案 1 :(得分:2)

您要做的是反向遍历数组:

let i = tests.length
while(i--) tests[i].testme()

这里正在起作用:

//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);

let i = tests.length
while(i--) tests[i].testme()

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