JavaScript比较两个对象是否相等的方法
本文实例讲述了JavaScript比较两个对象是否相等的方法。分享给大家供大家参考。具体如下:
在Python中可以通过cmp()内建函数来比较两个对象所包涵的数据是否相等(数组、序列、字典)。但是在javascript语言中并没有相关的实现。本js代码通过对js对象进行各方面的比较来判断两个对象是否相等
cmp=function(x,y){
//Ifbothxandyarenullorundefinedandexactlythesame
if(x===y){
returntrue;
}
//Iftheyarenotstrictlyequal,theybothneedtobeObjects
if(!(xinstanceofObject)||!(yinstanceofObject)){
returnfalse;
}
//Theymusthavetheexactsameprototypechain,theclosestwecandois
//testtheconstructor.
if(x.constructor!==y.constructor){
returnfalse;
}
for(varpinx){
//Inheritedpropertiesweretestedusingx.constructor===y.constructor
if(x.hasOwnProperty(p)){
//Allowscomparingx[p]andy[p]whensettoundefined
if(!y.hasOwnProperty(p)){
returnfalse;
}
//Iftheyhavethesamestrictvalueoridentitythentheyareequal
if(x[p]===y[p]){
continue;
}
//Numbers,Strings,Functions,Booleansmustbestrictlyequal
if(typeof(x[p])!=="object"){
returnfalse;
}
//ObjectsandArraysmustbetestedrecursively
if(!Object.equals(x[p],y[p])){
returnfalse;
}
}
}
for(piny){
//allowsx[p]tobesettoundefined
if(y.hasOwnProperty(p)&&!x.hasOwnProperty(p)){
returnfalse;
}
}
returntrue;
};
使用:
objA={
a:'123',
b:'456'
};
objB={
a:'123',
b:'000'
};
varisEqual=cmp(objA,objB);
console.log(isEqual);//false不相同
希望本文所述对大家的javascript程序设计有所帮助。