深拷贝

86 阅读1分钟
  1. 浅拷贝:拷贝对象和被被拷贝对象是共用的,拷贝对象在使用过程中也会改变被拷贝对象
  2. 深拷贝:拷贝对象和被拷贝对象互不影响,但是同用一个名字
function deepclone(obj) {
    if (typeof obj !== 'object' || obj == null) { //当obj不是对象类型或者是null类型,直接返回
        return obj;
    }
    let result;
    if (obj instanceof Array) {
        result = [];
    } else {
        result = {};
    }
    for (let key in obj) {
        result[key] = deepclone(obj[key]);
    }
    return result;
}