I am modifying the nested list and adding to an array now when I modify nested list it behaving very strangely, I am missing something very small but don’t know what.
class Square {
constructor() {
this.value = null;
this.next = null;
}
}
let square = new Square();
square.value = [0, 0];
let arrayOfValues = [[1,2], [2, 3], [4, 5]];
let resultArray = [];
arrayOfValues.forEach(v => {
let copy = square;
while (copy.next !== null) {
copy = copy.next;
}
let nextNode = new Square()
nextNode.value = v;
copy.next = nextNode;
resultArray.push(square);
})
console.log(resultArray) //[{value: [0, 0], next: {value: [1, 2], next: {value: [2, 3], next: {value: [4, 5], next: null}}}},....]
// want to return [{value: [0, 0], next: {value: [1, 2], next: null}}, ....]
2
Answers
Use this corrected version:
The problem is in this line:
Objects (and inherently arrays) are passed reference in Javascript, so after this line copy and square are both pointing to the same object.
to create a copy you need to initiate a new instance and copy the values. you can create a copy method in the class or simply create a new instance.