// 浅拷贝
Object.assign()
剩余运算符
// 深拷贝
// 第一种,但是会有正则变为空对象/function消失/日期变为字符串/Symbol、undefined消失/BigInt报错的问题
let newObj = JSON.parse(JSON.stringify(obj))
// 第二种
function deepClone(obj){
const constructor = obj.constructor;
if(obj === null) return null;
if(typeof obj !== "object") return obj;
if(/^(RegExp|Date)$/i.test(constructor.name)) return new constructor(obj);
let clone = new obj.constructor();
for(let key in obj){
if(!obj.hasOwnProperty(key)) break;
clone[key] = cloneDeep(obj[key]);
}
return clone;
}
// 深比较
// 基础数据类型,===
// 函数,正则,日期,转换为字符串
function _is(val1,val2){
const type1 = val1 === null ? 'null' : typeof val1;
const type2 = val2 === null ? 'null' : typeof val2;
if(type1 === "function" && type2 === "function"){
return val1.toString() === val2.toString();
}
if(type1 === "object" && type2 === "object"){
const ct1 = val1.constructor,
ct2 = val2.constructor;
if((ct1 === RegExp && ct2 === RegExp) || (ct1 === Date && ct2 === Date)){
return val1.toString() === val2.toString();
}
const keys1 = Object.keys(val1),
keys2 = Object.keys(val2);
if(keys1.length !== keys2.length) return false;
for(let i = 0;i < keys1.length;i++){
let key1 = keys1[i],
key2 = keys2[i];
if(key1 !== key2) return false;
let item1 = val1[keys1],
item2 = val2[keys2];
let flag = _is(item1,item2);
if(!flag) return false;
}
return true;
}
return val1 === val2;
}
对象和数组的深浅拷贝,深浅比较
最新推荐文章于 2023-03-17 19:35:00 发布