【发布时间】: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
【问题讨论】:
-
@jmargolisvt 哦,这对我的例子来说是完美的。但是在我的真实项目中,调用需要来自对象内部。所以理论上我可以运行
testme函数,如果测试失败设置一个标志,例如this.remove = 1。之后,我使用过滤器功能并过滤该标志。这会奏效。我想知道,这是一种有效的方法吗?
标签: javascript arrays