js深浅拷贝

浅拷贝:

1、对象:Object.assign()、{...obj1}

2、数组:Array.prototype.slice(arr1)

深拷贝:

1、简单封装函数

function deepClone(obj){
            if(obj === null) return null;
            if(typeof obj !== 'object') return obj;
            if(obj instanceof Date) return new Date(obj);
            if(obj instanceof RegExp) return new RegExp(obj);
            let copy = new obj.constructor();
            Object.keys(obj).forEach(key=>{
                copy[key] = deepClone(obj[key])
            })
            return copy
        }

 2、JSON.parse(JSON.Stringify(obj))存在诸多问题,如果属性值是Date、RegExp等复杂数据类型,则会出问题

原文地址:https://www.cnblogs.com/zmyxixihaha/p/13279288.html