JS判断两个数组或对象是否相同的方法示例
本文实例讲述了JS判断两个数组或对象是否相同的方法。分享给大家供大家参考,具体如下:
JS判断两个数组是否相同
要判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。
JSON.stringify([1,2,3].sort())===JSON.stringify([3,2,1].sort());//true
或者
[1,2,3].sort().toString()===[3,2,1].sort().toString();//true
经验证,上述方法对复杂数组结构不适用。
JS判断两个对象是否相同
这是网上某大神封装对比对象是否相同的function。
letcmp=(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;
};
经检测,同样也不支持复杂数据结构的对象。
一般情况下用的话上述2种方法已经够用了,拿来作比较的一般都是简单的数据结构。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《javascript面向对象入门教程》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。