Can somebody explain to me why the output is different?
I remove one element in both cases so why does the for loop make a difference between splice and reasigning the value?
filter:
1 2 3 4 5
splice:
1 2 3 5
let arr = [];
let arr2 = [];
class test {
constructor(s) {
this.s = s;
}
destroy() {
arr = arr.filter((e) => e !== this);
}
destroy2() {
var index = arr2.indexOf(this);
if (index !== -1) {
arr2.splice(index, 1);
}
}
}
arr.push(new test("1"));
arr.push(new test("2"));
arr.push(new test("3"));
arr.push(new test("4"));
arr.push(new test("5"));
arr2.push(new test("1"));
arr2.push(new test("2"));
arr2.push(new test("3"));
arr2.push(new test("4"));
arr2.push(new test("5"));
console.log("filter: ");
for (let t of arr) {
if (t.s === "3") {
t.destroy();
}
console.log(t.s);
}
console.log("nsplice: ");
for (let t of arr2) {
if (t.s === "3") {
t.destroy2();
}
console.log(t.s);
}