0
点赞
收藏
分享

微信扫一扫

JSON.parse(JSON.stringify())进行深拷贝的问题

七公子706 2022-01-15 阅读 56

标题JSON.parse(JSON.stringify())进行深拷贝的问题

问题描述:

上代码:

const log = console.log.bind(document);
function a(){
    log(12)
}
const data = [0,"a",null,undefined,NaN,a,{
    a:0,
    b:a,
    c:undefined,
    d:null,
    f:NaN,
    e:function(){},
    
}];
log(data)
log(JSON.parse(JSON.stringify(data)))
/** 0: 1
    1: "a"
    2: null
    3: null
    4: null
    5: {a: 1, b: 'a', d: null, f: null}
*/

利用递归实现深度拷贝

log(deepCopy(data))
//辅助函数,判断类型
function checkType(data){
    return Object.prototype.toString.call(data).slice(8,-1);
}
//深度拷贝
function deepCopy(data){
    let obj;
    // 判断类型
    const type = checkType(data);
    if(type === 'Object'){
        obj = {};
        for (const key in data) {
            if (Object.hasOwnProperty.call(data, key)) {
                const val = data[key];
                obj[key] = deepCopy(val);
            }
        }
    }else if(type === 'Array'){
        obj = [];
        for (const val of data) {
            obj.push(deepCopy(val));
        }
    }else{
        return data;
    }
    return obj;
}
举报

相关推荐

0 条评论