实现一个方法,只要内容形态一致,则认为数组或对象相等
let obj1 = {a:[1,'2'],b:2};
let obj2 = {b:2,a:[1,'2']};
let arr1 = [1,2,{a:{c:1},b:2},'miya'];
let arr2 = [1,2,{b:2,a:{c:1}},"miya"];
var obj3 = {a:[1,'2',{name:'miya',age:18}],b:{c:[3,1,2]}};
var obj4 = {b:{c:[3,1,2]},a:[1,'2',{age:18,name:'miya'}]};
//比如上面的
obj1 === obj2
arr1 === arr2
obj3 === obj4
答案:
function eql01(obj1,obj2){
if(Object.prototype.toString.call(obj1) !== Object.prototype.toString.call(obj2)){
return false;
}
let sortObj = (r1,r2)=>{
let obj = {}
for(var i in r1){
if(!r2[i]) return false;
obj[i] = r2[i];
}
Object.assign(obj,r2);
return obj;
}
if(Array.isArray(obj1)){
obj1.map((val,key)=>{
if(Object.prototype.toString.call(val) === "[object Object]"){
let ss = sortObj(val,obj2[key]);
obj2[key] = ss;
}
})
}else{
let gg = sortObj(obj1,obj2);
obj2 = gg;
}
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
eql02应该是最终版本了
function eql02(obj1,obj2){
if(Object.prototype.toString.call(obj1) !== Object.prototype.toString.call(obj2)){
return false;
}
if(Array.isArray(obj1)){
obj1.map((val,key)=>{
if(Object.prototype.toString.call(val) === "[object Object]"){
obj2[key] = Object.assign(val,obj2[key]);
}
})
}else{
obj2 = Object.assign(obj1,obj2);
}
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
如果你有更好的答案,请在下方留言加入讨论!谢谢