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);
}
Please refer below piece of code.
Here the arr is part of the iterator, and you are changing the array within the for loop, but the iterator will be referring to memory location of arr.
But, you just assigned different location/memory to arr variable, but the iterator is still referring to old memory/location.
In case of splice, it modifies the contents of the memory, in case of filter it's just new object assignment.
for(let a of arr) {
arr = arr.filter(i => i!=3); console.log(a); console.log(arr);
}