Strange behavior with arrays and slice

I was playing with some arrays in JavaScript when I came across something strange. Here is my code:

var origArray = new Array("one","two","three","four","five","six","seven","eight"); var newArray = origArray.slice(1,3); origArray[1] = "octopus"; console.log(newArray.join()); //prints two,three var origArray = new Array(["one","two"],["three","four"],["five","six"],["seven","eight"]); var newArray = origArray.slice(1,3); origArray[1][0] = "octopus"; console.log(newArray.join()); //prints octopus,four,five,six 

I do not understand why newArray affects the second case, and not the first. What's going on here?

+4
source share
2 answers

This is the difference between shallow copy and deep copy.

slice result is a different object than the original, but this does not mean that the objects inside the array (up to the end) are duplicated. If these internal objects are arrays, they are split between the copy and the original.

+6
source

Since arrays are links, then the slice will copy the links, not the values.

0
source

All Articles