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]
世界只因有你2017-07-05 10:41:07
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 array
To sum up the above two points, changing arr will naturally change arrnew
習慣沉默2017-07-05 10:41:07
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:
let arrnew = [...arr];