【问题标题】:How can I remove an item from an array while I use forEach on this array? [duplicate]当我在这个数组上使用 forEach 时,如何从数组中删除一个项目? [复制]
【发布时间】:2019-11-22 12:13:22
【问题描述】:

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

有什么好的方法可以解决这个问题?

这里是一个例子。运行该示例,您将看到在 forEach 循环中跳过了 2ed Object 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 

【问题讨论】:

标签: javascript arrays


【解决方案1】:

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

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

【讨论】:

  • 这需要修改现有的testme函数
  • 对于我的真实项目,我无法使用返回值,但我可以设置一个标志(请参阅我对 jmargolisvts commet 的回答)。我想知道哪个更有效。在我完成 forEach 循环后对数组使用 filter 方法,或者使用拼接,但使用 GetOfMyLawns 答案中的技巧(在数组上向后循环),然后在数组中使用拼接。
  • 是的,但它会更简单,只需return this.n &gt;= 3)
  • 是的,我的评论只是一个注释,没有修改,最终结果在我的测试中是0。
【解决方案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

【讨论】:

  • 很酷的工作!如果我稍后再次向数组中添加新对象,这也会起作用,对吧?
  • 是的,当您添加/删除/修改数组时它会起作用。
猜你喜欢
  • 2020-07-17
  • 1970-01-01
  • 2015-08-19
  • 2021-09-10
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
相关资源
最近更新 更多