深拷贝&浅拷贝

2021-03-27  本文已影响0人  Angel_6c4e
let obj = {
 a:1, //第一级属性
 b:2,
 c: {
   d:4, //第二级属性
   e:[1,2,3,4]
 } 
}

//for...in...
function simpleClone (obj) {
  let cloneObj = {};
  for (let i in obj) {
    cloneObj[i] = obj [i];
  }
  return cloneObj ;
}

//forEach + Object.getOwnpropertyNames(obj) 这个相当于ES6中的Object.keys(obj)
function simpleClone (obj) {
  let cloneObj = {};
  Object.getOwnpropertyNames(obj).forEach((key) => {
    cloneObj[key] = obj[key];
  })
  return cloneObj ;
}

//for...of... + Object.keys(obj) 或 Object.entries(obj)
function simpleClone (obj) {
  let cloneObj = {};
  for (let key of Object.keys(obj)) {
    cloneObj[key ] = obj [key ];
  }
  return cloneObj ;
}

function simpleClone (obj) {
  let cloneObj = {};
  for (let [key,value] of Object.entries(obj)) {
    cloneObj[key] = value;
  }
  return cloneObj ;
}

//Object.assign({},obj)
let obj1 = Object.assign({},obj)

//ES6中解构赋值
let obj2 = {...obj};
let obj = {
 a:1, //第一级子属性
 b:{
   c:3,//第二级子属性
   d:{
     e:5, //第三级子属性
     f:[1,2,3,4,5,6]
   }
 }
}
//递归遍历
function deepClone (obj,cloneInit) {
  let cloneObj = cloneInit || {};
  for(let i in obj) {
    if(typeof obj[i] === 'object' && obj[i] !== null){
      cloneObj[i] = Array.isArray(obj[i]) ? [] : {}
      deepClone (obj[i],cloneObj[i]);
    } else {
      cloneObj[i] = obj[i]
    }
  }
  return cloneObj ;
}

//JSON.parse() + JSON.tringify()
let obj1 = JSON.parse(JSON.stringify(obj))

//jquery的extend()
let obj2 = $.extend(true,{},obj);
上一篇 下一篇

猜你喜欢

热点阅读