js比较两个单独的数组或对象是否相等的实例代码
所谓js的中的传值,其实也就是说5种基本数据类型(null,undefind,boolean,number,string)
传引用也就是说的那个引用数据类型,(array和object)
基本数据类型的值不可变,而引用数据类型的值是可变的
所以当你比较数组和对象时,都是false;除非你是克隆的原份数据
即:vara={name:"李四"};varb=a;
大家通常称对象为引用类型,以此来和基本类型进行区分;而对象值都是引用,所以的对象的比较也叫引用的比较,当且当他们都指向同一个引用时,即都引用的同一个基对象时,它们才相等.
1.比较两个单独的数组是否相等
JSON.stringify(a1)==JSON.stringify(a2)
或
a1.toString()==a2.toString()
要判断2个数组是否相同,把数组转换成字符串进行比较。
如果要比较两个数组的元素是否相等,则:
JSON.stringify([1,2,3].sort())===JSON.stringify([3,2,1].sort());
或
[1,2,3].sort().toString()===[3,2,1].sort().toString();
判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。
2.比较两个单独的对象是否相等
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;
};
下面是StackOverflow大神封装的方法,可以学习一下:
1.比较数组
//Warnifoverridingexistingmethod
if(Array.prototype.equals)
console.warn("OverridingexistingArray.prototype.equals.Possiblecauses:NewAPIdefinesthemethod,there'saframeworkconflictoryou'vegotdoubleinclusionsinyourcode.");
//attachthe.equalsmethodtoArray'sprototypetocallitonanyarray
Array.prototype.equals=function(array){
//iftheotherarrayisafalsyvalue,return
if(!array)
returnfalse;
//comparelengths-cansavealotoftime
if(this.length!=array.length)
returnfalse;
for(vari=0,l=this.length;i
2.比较对象
Object.prototype.equals=function(object2){
//Forthefirstloop,weonlycheckfortypes
for(propNameinthis){
//Checkforinheritedmethodsandproperties-like.equalsitself
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
//Returnfalseifthereturnvalueisdifferent
if(this.hasOwnProperty(propName)!=object2.hasOwnProperty(propName)){
returnfalse;
}
//Checkinstancetype
elseif(typeofthis[propName]!=typeofobject2[propName]){
//Differenttypes=>notequal
returnfalse;
}
}
//Nowadeepercheckusingotherobjectspropertynames
for(propNameinobject2){
//Wemustcheckinstancesanyway,theremaybeapropertythatonlyexistsinobject2
//Iwonder,ifrememberingthecheckedvaluesfromthefirstloopwouldbefasterornot
if(this.hasOwnProperty(propName)!=object2.hasOwnProperty(propName)){
returnfalse;
}
elseif(typeofthis[propName]!=typeofobject2[propName]){
returnfalse;
}
//Ifthepropertyisinherited,donotcheckanymore(itmustbeequaifbothobjectsinheritit)
if(!this.hasOwnProperty(propName))
continue;
//Nowthedetailcheckandrecursion
//Thisreturnsthescriptbacktothearraycomparing
/**REQUIRESArray.equals**/
if(this[propName]instanceofArray&&object2[propName]instanceofArray){
//recurseintothenestedarrays
if(!this[propName].equals(object2[propName]))
returnfalse;
}
elseif(this[propName]instanceofObject&&object2[propName]instanceofObject){
//recurseintoanotherobjects
//console.log("Recursingtocompare",this[propName],"with",object2[propName],"bothnamed\""+propName+"\"");
if(!this[propName].equals(object2[propName]))
returnfalse;
}
//Normalvaluecomparisonforstringsandnumbers
elseif(this[propName]!=object2[propName]){
returnfalse;
}
}
//Ifeverythingpassed,let'ssayYES
returntrue;
}
总结
以上所述是小编给大家介绍的js比较两个单独的数组或对象是否相等的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!