javascript - Array assignment problem
高洛峰
高洛峰 2017-07-05 10:39:07
0
4
662

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]

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
世界只因有你
  1. Arrays are also objects and reference types. When assigning, the address is assigned and a new object will not be cloned for assignment.

  2. sort will change the original array

To 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:

let arrnew = [...arr];
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template