深拷贝对象
deepClone(obj) {
if (obj === null) return null;
if (typeof obj !== 'object') return obj;
if (obj instanceof Date) {
let date = new Date();
date.setTime(obj.getTime());
return date;
}
let cloneObj = new obj.constructor();
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key]);
}
}
return cloneObj;
}
使用
let tmpObj = {name: '小王商铺', num: 16, list: [{goodsName: '茄子', price: 350}, {goodsName: '青瓜', price: 100}]}
console.log('clone obj:', deepClone(objs));
let tmpDate = {time: new Date('2022-09-08')}
console.log('clone date:', deepClone(date))