Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript Array.slice(0) return a shallow copy? [duplicate]

Tags:

javascript

IIUC Array.slice(0) returns a copy of the array. Is it a shallow copy? In other words the array items still have the same memory location, but the array container gets assigned a new one?

Effectively:

let oldArray = ['old', 'array'];
let newArray = oldarray.slice(0);
let same = oldArray[0] === newArray[0]; //true 
let same = oldArray === newArray; //false
like image 623
Ole Avatar asked Apr 18 '18 02:04

Ole


2 Answers

Yes,see demo:

var o = [{
  x: 1
}]
var o2 = o.slice(0)
o2[0].x = 2
console.log(o[0].x)
like image 87
xianshenglu Avatar answered Oct 17 '22 12:10

xianshenglu


You are correct - it does create a shallow copy.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

If you are wanting a deep copy you can do the ye ole dirty dirt:

var arr = [1]; 
var arr2 = JSON.parse(JSON.stringify(arr));

arr[0] = 99;
arr2[0] = 1000;

console.log({arr, arr2});
like image 37
Zze Avatar answered Oct 17 '22 12:10

Zze