arrays equality in Java Script [duplicate]

1

Good afternoon, I have this little program:

let oi=[1,2,3,4]

let xau=[]
xau=oi

xau[2]=7
console.log(oi)

My problem is that when in the console the output is:

[1,2,7,4]

According to what I understand, xau should be a new instance that has the values of hi, but when modifying xau, tbm modifico hi, if someone can explain to me why this is happening and how do I can modify xau without modifying hi, I am grateful

    
asked by anonymous 06.03.2018 / 19:50

3 answers

6

In Javascript, arrays and objects are passed by reference. So you can edit the values of the array oi through the variable xau , since both point to the same array.

You can create a copy of the oi array and assign it to xau using the .slice .

let oi=[1,2,3,4]

let xau=oi.slice()

xau[2]=7
console.log(oi, xau)
    
06.03.2018 / 19:57
0

Another way is to use .map() :

let oi=[1,2,3,4]

let xau = oi.map(Number)

xau[2]=7
console.log(oi, xau)

The .map() will generate a new independent array with the oi values.

    
06.03.2018 / 20:55
0

The problem has already been explained by @PanterA, but to stay as a reference to future readers I leave here another way to create a copy of the array using concat :

let xau = oi.concat()

The concat serves to concatenate the array with what is passed by parameter. Nothing happens but only the original array.

Example:

let oi=[1,2,3,4]

let xau=oi.concat()

xau[2]=7
console.log(oi, xau)

Using ES6 and spread operator can make the copy even simpler with:

let xau = [...oi]

See it working:

let oi=[1,2,3,4]

let xau= [...oi]

xau[2]=7
console.log(oi, xau)
    
06.03.2018 / 22:57