ntscshen / ntscshen.github.io

个人博客
0 stars 2 forks source link

JS经典interview(八) - 深浅拷贝 #9

Open ntscshen opened 6 years ago

ntscshen commented 6 years ago

JS的深浅拷贝

浅拷贝 1、Object.assign(); 2、扩展运算符的合并; 3、concat\slice 数组浅拷贝

深拷贝 1、JSON.parse(JSON.stringify(xxx)); 只能拷贝被JSON数据结构识别的 2、$.extend(xxx); 3、_.cloneDeep(xxx);

手动实现一个深度拷贝

// 1、各种类型判断
// 2、保留继承关系
// 3、递归拷贝
function deepClone(obj) {
  if (typeof obj !== 'object') return obj;
  if (obj == null) return null;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  let o = new obj.constructor();// 保留类的继承关系
  for (let key in obj) {
    o[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
  }
  return o;
}
ntscshen commented 2 years ago

浅拷贝

...
Object.assign
[].concat()
arr.slice(0)
// 1. 扩展运算符
const arr = ['lin', 'is', 'handsome']
const newArr = [...arr]
// 2. Object.assign
const obj = {
  name: 'lin'
}
const newObj = Object.assign({}, obj)
// 3. slice
const arr = ['lin', 'is', 'handsome']
const newArr = arr.slice(0)
// 4. concat
const arr = ['lin', 'is', 'handsome']
const newArr = [].concat(arr)

深拷贝

let obj = {
    numberParams:1,
    functionParams:() => {
        console.log('昨天基金全是绿的,只有我的眼睛是红的');
    },
    objParams:{
        a:1,
        b:2
    }
}

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

const temp = copyObj(obj);
console.log(temp === obj)
temp.numberParams = 999;
obj.numberParams = 222;
console.log('obj: ', obj);
console.log('temp: ', temp)