0
点赞
收藏
分享

微信扫一扫

js手写深度克隆数组和对象

大南瓜鸭 2022-02-13 阅读 41
function deepClone(obj) {
    if (typeof obj !== 'object') {
        return obj;
    }
    if (Array.isArray(obj)) {
        return deepCloneArray(obj);
    } else {
        return deepCloneObject(obj);
    }

}

function deepCloneArray(arr) {
    const target = [];
    arr.forEach(it => {
        if (typeof it === 'object') {
            target.push(deepClone(it));
        } else {
            target.push(it);
        }
    })
    return target;

}

function deepCloneObject(obj) {
    const target = {};
    for (const prop in obj) {
        if (Object.hasOwnProperty.call(obj, prop)) {
            if (typeof obj[prop] === 'object') {
                target[prop] = deepClone(obj[prop]);
            } else {
                target[prop] = obj[prop];
            }
        }
    }
    return target;

}
举报

相关推荐

0 条评论