深度克隆deepClone

298 阅读1分钟
    实现思路
    因为js的数据类型可分为两大类 1原始类型 2引用类型
    当数据为原始类型的时候我们就直接返回
    当数据为引用类型的时候我们就创建一个新的对象或者数组
    
    function deepClone(datas){
        if(Array.isArray(datas)){
            const newArr = []
            datas.forEach((item,index)=>{
                newArr[index] = deepClone(item)
            })
            return newArr
        }
        if(typeof datas === 'Object' && datas !== null){
            const newObj = {}
            for(const key in datas) {
                newObj[key] = deepClone(datas[key])
            }
            return newObj
        }
        return datas
    }