工作总结

js:深拷贝对象、深拷贝数组

2019-10-31  本文已影响0人  轩轩小王子
//深拷贝对象
export function deepCopy(obj) {
    let tempObj = {};
    if (Object.prototype.toString.call(obj) == "[object Object]") {
        for (var attr in obj) {
            if (Object.prototype.toString.call(obj[attr]) == "[object Object]") {
                tempObj[attr] = deepCopy(obj[attr]);
            } else if (Object.prototype.toString.call(obj[attr]) == "[object Array]") {
                tempObj[attr] = copyArray(obj[attr]);
            } else {
                tempObj[attr] = obj[attr];
            }
        }
    }
    return tempObj;
}
//深拷贝数组
export function copyArray(arr) {
    let tempArr = [];
    if (Object.prototype.toString.call(arr) == "[object Array]") {
        arr.forEach(function(item) {
            if (Object.prototype.toString.call(item) == "[object Object]") {
                tempArr.push(deepCopy(item));
            } else if (Object.prototype.toString.call(item) == "[object Array]") {
                tempArr.push(copyArray(item));
            } else {
                tempArr.push(item);
            }
        })
    }
    return tempArr;
}

上一篇 下一篇

猜你喜欢

热点阅读