数组的深拷贝、浅拷贝

2020-04-15  本文已影响0人  jane819
一.数组的浅拷贝,引用之间的拷贝,没有实现真正的拷贝
const arr = [1,2,3]
const arr1 = arr
arr1.push(2)
console.log(arr,arr1)
二.深拷贝
  1.传统做法:for循环遍历
  const arr = [1,2,3]
  const arr1 = []
  for(var i =0;i<arr.length;i++){
    arr1[i] = arr[i]
  }
  arr[i].push(3)
  console.log(arr,arr1)
  2.es6 Array.from实现数组深拷贝
    const arr = [1,2,3]
    const arr1 = Array.from(arr)
    arr1.push(4)
     console.log(arr,arr1)
   3.es6 .[..arr]实现数组深拷贝
    const arr = [1,2,3]
    const arr1 = [...arr]
    arr1.push(4)
     console.log(arr,arr1)
上一篇下一篇

猜你喜欢

热点阅读