I have an array with functions/Objects in it. This Objects have a function to test itself and if they fail they get removed from the array. If I run a forEach on this array and run this testfunction and one object gets removed from the array the forEach loop skips an object.
What is a good way to solve this problem?
Here a example. Run the example and you will see the the 2ed Object tests.push(new Test(2));
is skipped in the forEach loop.
//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