JS实现对象深拷贝的几种方法

遍历+递归

function deepClone(obj){
  let newObj =  {}
  for(let key in obj){
      if(obj.hasOwnProperty(key)){
          if(typeof(obj[key]) === 'object' && obj[key] !== null){
            newObj[key] = (Array.isArray(obj[key])  ? [] : {})
            newObj[key] = (Array.isArray(newObj[key]) ? [...obj[key]] : deepClone(obj[key]));  
          }else{
              newObj[key] = obj[key];
          }
      }
  }
  return newObj;
}

Object.assign + 递归

function deepClone(obj){
  let newObj = {}
  for(let key in obj){
    if(obj.hasOwnProperty(key)){
      newObj[key] = (typeof obj[key] === 'object' ? Object.assign(obj[key]) : obj[key])
    }
  }
  return newObj
}

对象扩展 + 递归

function deepClone(obj){
  var newObj ={}
  for(let key in obj){
    if(obj.hasOwnProperty(key)){
      if(typeof obj[key] === 'object'){
        newObj[key] = (Array.isArray(obj[key]) ? [] : {})
        newObj[key] = (Array.isArray(newObj[key]) ? [...obj[key]] : {...obj[key]}) 
      } 
      else{
        newObj[key] = obj[key]
      }
    }
  }
  return newObj
}

JSON复制

对NAN和undefined无法正确复制

function deepClone(obj){
  var newObj = JSON.parse(JSON.stringify(obj))
  return newObj
}

测试对象

var obj = {
    name:'lily',
    age:23,
    homework:{
      math:'not complite',
      chinese:'complite'
    },
    extra:{
      num:NaN,
      under:undefined,
      empty:null
    },
    arr:[1,2,3,4]
  }
  console.log(deepClone(obj))

第三方库:lodash或者jQuery的extend方法

$.extend(true,object1,object2) //深拷贝
$.extend(object1,object2) //浅拷贝

你可能感兴趣的:(前端开发)