Loading

js简单实现一个深拷贝

function deepClone(target) {
    if(typeof target !== "object") return target // 退出条件
    if(Array.isArray(target)){ // 判断数组
        const res = []
        for(const i of target){
             res.push(Array.isArray(i) ? deepClone(i) : i)
        }
        return res
    } else if(isObject(target)){ // 判断对象
        const res = {}
        Object.keys(target).forEach(key => {
            const v = target[key]
            res[key] = isObject(v) ? deepClone(v) : v
        })
        return res
    } 
}

function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
  }

  const test = [1,2,3,4,{a:1,b:{c:2}}] 

console.log(JSON.stringify(deepClone(test)));
posted @ 2021-01-20 21:53  不吃苦瓜^  阅读(66)  评论(0编辑  收藏  举报