JavaScript深度复制

简单的深度复制一个数组

let copyArray = (array)=>{
    return Array.prototype.slice.call(array)
}
//或者
copyArray = (array)=>array.map(v=>v);

简单的复制一个对象

let copyObject = (object)=>{
    return Object.assign({},object)
}

那么如何完成一个深度复制任何对象的方法呢(包含嵌套的情况)

let isArray = (array)=>{
    return Object.prototype.toString.call(array)==='[object Array]'
}
let isObject = (object)=>{
    return Object.prototype.toString.call(array)==='[object Object]'
}
let deepCopy = (source)=>{
    if( isArray(source) ){
        return copyArray(source).map(v=>isArray(v)||isObject(v)?deepCopy(v):v)
    }else if( isObject(source) ){
        let attrs = Object.keys( copyObject(source) )
        let newObj = Object.create(null);
        attrs.forEach(v=>{
            let temp = source[v];
            newObj[v] = isArray(temp)||isObject(temp)?deepCopy(temp):temp
        })
        return newObj
    }else {
        return source
    }
}

你可能感兴趣的:(js)