拷贝

1.浅拷贝

浅拷贝:for...in   三点运算符  Object.assign()  Array.prototype.slice()   Array.prototype.concat()等

2.深拷贝

2.1.JSON.parse(JSON.stringify(obj))

    问题:

   不能考本function
不能拷贝原型链中的属性
不能正确处理Date和Regexp数据
会忽略undefined和symbol

2.2 deepClone()

function deepClone(obj){
    // 日期和正则new
    if(obj instanceof RegExp) return new RegExp(obj)
    if(obj instanceof Date) return new Date(obj)
    // 普通类型直接返回
    if(obj === null || typeof obj !== 'object'){
         return obj
    }
    // 判断是数组中还是对象 - 只拷贝自生属性
    let result;
    if(obj instanceof Array){
        result = []
    }else{
         result = {}
    }

    for(let key in  obj){
        if(obj.hasOwnProperty(key)){
            result[key] = deepClone(obj[key])
        }
    }
    return result
} const obj1
= deepClone(obj) obj1['friends'][3] = 'jiaqi' obj1['others']['flow'] = 'jiaqi'
console.log(obj1)

 

posted @ 2021-08-18 14:52  卷叶小树  阅读(97)  评论(0编辑  收藏  举报