wangyuan0108 / fe-qa

知识和笔记,整理分享,以便提升和巩固
https://github.com/wangyuan0108/blog/issues
13 stars 0 forks source link

简单实现一个深拷贝的方法 #100

Open wangyuan0108 opened 3 years ago

wangyuan0108 commented 3 years ago
var parent = {
  age: 20,
  hobby: [1, 2, 3],
  home: {city: '杭州'},
};
var child = extendDeep(parent);
child.age = 26;
child.hobby.push('4');
child.home.city = '上海';
console.log('child ', child); //[1, 2, 3, 4]
console.log('parent ', parent);

function extend(parent) {
  let child;
  if (Object.prototype.toString.call(parent) == '[object Object]') {
    child = {};
    for (let key in parent) {
      child[key] = extend(parent[key])
    }
  } else if (Object.prototype.toString.call(parent) == '[object Array]') {
    child = parent.map(item => extend(item));
  } else {
    return parent;
  }
  return child;
}

function extendDeep(parent, child) {
  child = child || {};
  for (var key in parent) {
    if (typeof parent[key] === "object") {
      child[key] = (Object.prototype.toString.call(parent[key]) === "[object Array]") ? [] : {};
      extendDeep(parent[key], child[key]);
    } else {
      child[key] = parent[key];
    }
  }
  return child;
}
wangyuan0108 commented 3 years ago
const newObj = JSON.parse(JSON.stringify(oldObj))