当前位置:网站首页>JS handwriting depth clone array and object

JS handwriting depth clone array and object

2022-06-25 05:05:00 I am Feng Feng Yi

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;

}
原网站

版权声明
本文为[I am Feng Feng Yi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210527410509.html