search

Home  >  Q&A  >  body text

javascript - Array assignment problem

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]

高洛峰高洛峰2781 days ago685

reply all(4)I'll reply

  • 世界只因有你

    世界只因有你2017-07-05 10:41:07

    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

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-05 10:41:07

    let arrnew = arr.slice()

    reply
    0
  • 高洛峰

    高洛峰2017-07-05 10:41:07

    This article will be of great help to you! click me

    reply
    0
  • 習慣沉默

    習慣沉默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];

    reply
    0
  • Cancelreply