JavaScript比较两个数组的内容是否相同(推荐)
今天意外地发现JavaScript是不能用==或===操作符直接比较两个数组是否相等的。
alert([]==[]);//false alert([]===[]);//false
以上两句代码都会弹出false。
因为JavaScript里面Array是对象,==或===操作符只能比较两个对象是否是同一个实例,也就是是否是同一个对象引用。目前JavaScript没有内置的操作符判断对象的内容是否相同。
但是惯性思维让人以为数组也是值,是可以比较的。
如果要比较数组是否相等,就只能遍历数组元素比较。
在网上流传很普遍的一种做法是将数组转换成字符串:
JSON.stringify(a1)==JSON.stringify(a2)
或
a1.toString()==a2.toString()
请不要使用这种方法。
这种方法在某些情况下是可行的,当两个数组的元素顺序相同且元素都可以转换成字符串的情况下确实可行,但是这样的代码存有隐患,比如数字被转换成字符串,数字“1”和字符串“1”会被认为相等,可能造成调试困难,不推荐使用。
在StackOverflow上有大神已经提供了正确的方法,我就做下搬运工吧:
//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
大神还顺手给了比较Object的方法:
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;
}
以上所述是小编给大家介绍的JavaScript比较两个数组的内容是否相同(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!