arrays equality in Java Script

Asked

Viewed 235 times

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 on the console the impression that comes out 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 to do so that I can modify xau without modifying hi, I am grateful

3 answers

5


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

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

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

let xau=oi.slice()

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

  • thanks mt, did not know it was passed by reference, helped me mt

  • The answer is great, I’ll even vote +1. But just allow me one observation: the value 0 in the slice would be unnecessary. If you omit the parameters (leave empty, slice()) the value 0 is already assumed.

  • @dvd edited. Thank you for the suggestion.

0

The problem has already been explained by @Pantera, but to stay as 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. Passing nothing ends up receiving 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 the Operator spread can make the copy even simpler with:

let xau = [...oi]

See working:

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

let xau= [...oi]

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

0

Another way is by using .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 values of oi.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.