I want to unshift on a copy of the array, but the original array modifies too. Why is that?
var array1 = [1, 2, 3] var array2 = array1 array2.unshift(4, 5) console.log(array1) console.log(array2)
Try using Array.from()
var array1 = [1, 2, 3] var array2 = Array.from(array1) array2.unshift(4, 5) console.log(array1) console.log(array2)
Use spread operator ( ... )
to make second array. It will make a new array with new reference. And then perform your task.
var array1 = [1, 2, 3]; var array2 = [...array1]; array2.unshift(4, 5); console.log(array1); console.log(array2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.