Answer the question
In order to leave comments, you need to log in
Why, after assigning a value to a variable to another variable, does the array of the first variable change?
let aaa = [1,2,3]
let bbb = aaa
bbb.push(4)
console.log(aaa) // [1,2,3,4]
Answer the question
In order to leave comments, you need to log in
Because both variables (aaa and bbb) refer to the same object.
You can do this:
let aaa = [1,2,3]
let bbb = [...aaa ] // не обязательно через spread, можно чем угодно, что делает копию. slice, например.
bbb.push(4)
console.log(aaa) // [1,2,3]
console.log(bbb) // [1,2,3,4]
https://jsfiddle.net/s716xeq9/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question