I don’t understand why pushing to the array affects the result, while changing the array items does not.
How can this be written so that the restore method returns the initial array?
class Snapshot {
constructor(array) {
this.array = [...array];
}
restore() {
return this.array;
}
}
var array = [1, 2];
var snap = new Snapshot(array);
array[0] = 3;
array = snap.restore();
console.log(array.join()); // Logs "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2", but logs "1,2,4"
>Solution :
This line…
array = snap.restore();
assigns the object reference of snap.array to array so they are referring to the same object value. Manipulating array at this stage also manipulates snap.array.
If you want to break references and prevent external manipulation of class members, you want this instead
restore() {
return [...this.array]
}