我知道的深拷贝与浅拷贝

浅拷贝:
① 对象拷贝 Object.assign()

let obj1 = {
  name:'赵',
  age: 22
}
let obj2 = {}
Object.assign(obj2,obj1)
console.log(obj2)

② 对象拷贝 …扩展运算符

let obj1 = {
  name:'赵',
  age:22
}
let obj2 = {...obj1}
console.log(obj2)

③ 数组拷贝 concat

let arr1 = [5,10,230]
let arr2 = []
let arr3 = arr2.concat(arr1)
console.log(arr1)

④ 数组拷贝 Array.from()

let arr1 = [5,10,30]
let arr2 = Array.from(arr1)
console.log(arr2)

⑤ 数组拷贝 扩展运算符

let arr1 = [5,10,20]
let arr2 = [...arr1]
console.log(arr2)

深拷贝:
① JSON.stringify() JSON.parse()

let obj = {
   name:'赵伟年',
   age:22,
   study:'在学js'
}
let str = JSON.stringify(obj)             // 变成字符串类型的对象
console.log(str)
let newObj = JSON.parse(str)             
console.log(newObj)

② 递归

let checkType = data => {
  return Object.prototype.toString.call(data).slice(8,-1) // 检查类型
} 
let deepClone = target => {
  let targetType = checkType(target)
  let result
  if(targetType === 'Object'){
    result = {}
  }else if(targetType === 'Array'){
    result = []
  }else {
    return target
  }
  for(let i in target){
    let value = target[i]
    let valueType = checkType(value)
    if(valueType === 'Object' || valueType === 'Array'){
      result[i] = deepClone(value)        // 递归
    }else {
      result[i] = value
    }
  }
  return result
}

猜你喜欢

转载自blog.csdn.net/weixin_43906597/article/details/114107966