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
Yes,see demo:
var o = [{
x: 1
}]
var o2 = o.slice(0)
o2[0].x = 2
console.log(o[0].x)
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With