Skip to content
大纲

对象的拷贝

浅拷贝

让变量指向某个对象的指针,共享指针,其中一成员修改内容,其他也跟着修改

浅拷贝方式

  1. Object.assign() 对象合并
js
let newObj = Object.assign({}, obj)
  • 合并一层相当于深拷贝,值不为数组,对象,可以是函数,类
  1. Array.concat() 数组合并
js
let newArr = [].concat(arr)
  • 合并一层相当于深拷贝,值不为数组,对象,可以是函数,类
  1. Array.slice() 数组截取
js
let newArr = arr.slice()
  • 合并一层相当于深拷贝,值不为数组,对象,可以是函数,类

深拷贝

  1. JSON.parse + JSON.stringify
js
let newObj = JSON.parse(JSON.stringify(obj))
  • undefined 会转为null
  • JSON.stringify() 第一个参数内的对象不能含有toJSON方法不然会被调用
  1. 递归复制

for in 拿健名,数组拿下标,for of 那元素,obj报错

js
function judgeType (target) {
    return Object.prototype.toString.call(target).slice(8, -1)
  }
  
  function deepCopy (obj) {
    let res = null
    let type = judgeType(obj)
    if (type === 'object') {
      res = {}
    } else if (type === 'array') {
      res = []
    } else {
      return obj
    }

    for(let i in obj) {
      let value = obj[i]
      let type = judgeType(value)
      if (type === 'object' || type === 'array') {
        res[i] = deepCopy(value)
      } else {
        res[i] = value
      }
    }

    return res
  }

Released under the MIT License.