方法一:JSON对象实现深拷贝
局限:function 、正则RegExp 、undefined 等不支持。
let obj = [1,2,3]; let newObj = JSON.parse(JSON.stringify(obj));//先把obj转化为字符串类型,再把字符串类型转化为数组类型。[1,2,3]
方法二:类型判断+递归实现深拷贝
比较完整的方法
//深拷贝功能函数 function deepClone(obj, hash = new WeakMap()) { //判断是null或undefined直接返回 if (obj == null) return obj; //number string boolean symbol 等基本类型直接返回 if (typeof obj !== \'object\') return obj;//是对象类型继续往下 //object //判断是日期,new一个日期并返回 if (obj instanceof Date) return new Date(obj); //判断是正则,new一个正则并返回 if (obj instanceof RegExp) return new RegExp(obj); if (hash.get(obj)) { return hash.get(obj); } //数组 空对象{} let newObj = new obj.constructor; hash.set(obj, newObj); for (let key in obj) { // obj无论是数组还是对象 都可以进行for in迭代 newObj[key] = deepClone(obj[key], hash); } return newObj; } //函数使用 let arr = [1, 2, 3, { a: 1, b: [1, 5] }]; console.log(deepClone(arr));//[1, 2, 3, { a: 1, b: [1, 5] }]