Why assign the value of arr to arrnew, and why does arrnew change when arr changes? If you want arrnew to get the data of arr, how to write it without following the operation after arr?
let arr=[1,2,3,4,5]
let arrnew=arr
arr=arr.sort((a,b)=>{return b-a})
console .log(arr)//[5, 4, 3, 2, 1]
console.log(arrnew)//[5, 4, 3, 2, 1]
Arrays are also objects and reference types. When assigning, the address is assigned and a new object will not be cloned for assignment.
sort
will change the original arrayTo sum up the above two points, changing arr will naturally change arrnew
let arrnew = arr.slice()
This article will be of great help to you! click me
Your assignment to
arrnew
is just a reference to the address.If you want to copy an array, you can use the spread operator, as follows: