W
W
wufapexef2018-03-20 01:43:00
JavaScript
wufapexef, 2018-03-20 01:43:00

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]

Why is this happening? How to add without changing the first array?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-03-20
@wufapexef

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 question

Ask a Question

731 491 924 answers to any question