const deepCopy = (target) => {
let rst
if(typeof target === 'object'){
if(Array.isArray(target)){
rst = []
target.forEach(item=>rst.push(deepCopy(item)))
}else if(target === null || target.constructor === RegExp){
rst = target
}else{
rst = {}
for(let item in target){
rst[item] = deepCopy(target[item])
}
}
}else{
rst = target
}
return rst
}
const obj = {
a:{
b:{
c:{
name:'123',
list:[1,2,3,4,5]
},
id:'1234'
},
name:'56'
},
list:[1,2,3,4,5,6]
}
function compare(data,target){
const dataType = typeof data
const targetType = typeof target
if(dataType !== targetType){
return false
}
if(dataType !== "object" ){
if(Number.isNaN(data) || Number.isNaN(target)){
return Number.isNaN(data) && Number.isNaN(target)
}
return data === target
}else{
if(!data || !target){
return data === target
}
if(target.constructor === RegExp || data.constructor === RegExp){
return data.toString() === target.toString()
}
if(Array.isArray(data) || Array.isArray(target)){
const rst = []
if(data.length !== target.length){
return false
}
for(let i = 0; i < data.length ; i++){
if(!compare(data[i],target[i])){
return false
}
}
return true
}
if(!compare(Object.keys(data),Object.keys(target))){
return false
}
for(let key in data){
if(!compare(data[key],target[key])){
return false
}
}
return true
}
}
console.log('--------------对象-----------------');
let newObj = deepCopy(obj)
console.log(compare(newObj,obj));
newObj.list.push(34)
console.log(compare(newObj,obj));
console.log('--------------数组[1,2],[1,2]-----------------');
console.log(compare([1,2],[1,2]));
console.log('--------------数组[[1,2],[1,2]]-----------------');
console.log(compare([[1,2],[1,2]],[[1,2],[1,2]]));
console.log('--------------数组[[1,2],[1,2]],[[1,2],[3,4]]-----------------');
console.log(compare([[1,2],[1,2]],[[1,2],[3,4]]));
console.log('--------------基础类型:1,1');
console.log(compare(1,1));
console.log(`--------------基础类型:1,'1'`);
console.log(compare(1,'1'));
console.log(`--------------基础类型:true,true`);
console.log(compare(true,true));
console.log(`--------------基础类型:Infinity,Infinity`);
console.log(compare(Infinity,Infinity));
console.log(`--------------基础类型:NaN,NaN`);
console.log(compare(NaN,NaN));
