海纳百川

深拷贝

2019-09-27  本文已影响0人  凛冬已至_123

下面总结几种深拷贝的方法:

function clone(target) {
  if(typeof target === 'object'){
    let copydata = Array.isArray(target)?[]:{}
    for(let key in target) {
      copydata[key] = clone(target[key])
    }
    return copydata
  }else {
    return target
  }
}
function clone(target, map = new Map()) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {};
        if (map.get(target)) {
            return map.get(target);
        }
        map.set(target, cloneTarget);
        for (const key in target) {
            cloneTarget[key] = clone(target[key], map);
        }
        return cloneTarget;
    } else {
        return target;
    }
}
上一篇下一篇

猜你喜欢

热点阅读