其他分享
首页 > 其他分享> > js 深拷贝函数

js 深拷贝函数

作者:互联网

function clone(obj) {
    if (typeof obj == "object") {
        if (Array.isArray(obj)) {
            let arr = [];
            for (let item of obj) {
                arr.push(Object.assign(clone(item)));
            }
            return arr;
        } else if (obj == null) {
            return null;
        } else {
            let obj1 = {};
            for (let index in obj) {
                obj1[index] = clone((obj[index]));
            }
            return obj1;
        }
    } else if (typeof obj == "function") {
        return Object.assign(obj);
    } else if (typeof obj == undefined) {
        return undefined;
    } else {
        return obj;
    }
}

export default clone
//自定义一个深拷贝递归函数
 function deepClone(obj){
        let clone = Array.isArray(s)?[]:{};
        for (const key in obj) {
            let item = obj[key];
            if(item){
                //实现方法的克隆
                if(item instanceof Function){
                    clone[key] = new Function('return '+item.toString())()
                }
                else if(item instanceof Object ){
                    clone[key] = deepClone(item);
                }
                else {
                    clone[key] = item;
                }
            }
        }
        return clone;
    }

标签:obj,函数,clone,js,item,let,return,拷贝,else
来源: https://www.cnblogs.com/whh666/p/16466402.html