在js前端面試過程中,經(jīng)常會遇到這樣的筆試題:JS中如何比較兩個Json對象是否相等實例代碼,下面小編抽點時間給大家整理下,一起看看吧。
1.先準(zhǔn)備三個工具方法,用于判斷是否是對象類型,是否是數(shù)組,獲取對象長度
function isObj(object) {
return object && typeof (object) == 'object' && Object.prototype.toString.call(object).toLowerCase() == "[object object]";
}
function isArray(object) {
return object && typeof (object) == 'object' && object.constructor == Array;
}
function getLength(object) {
var count = 0;
for (var i in object) count++;
return count;
}
2.準(zhǔn)備兩個相同或不同的Json對象
var jsonObjA = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [
{ "Age": "100" },
{
"Box": [
{ "Height": "100" },
{ "Weight": "200" }
]
}
],
"Address": "馬欄山"
}
var jsonObjB = {
"Name": "MyName",
"Company": "MyCompany",
"Infos": [
{ "Age": "100" },
{
"Box": [
{ "Height": "100" },
{ "Weight": "200" }
]
}
],
"Address": "馬欄山二號"
}
3.主要的代碼
function Compare(objA, objB) {
if (!isObj(objA) || !isObj(objB)) return false; //判斷類型是否正確
if (getLength(objA) != getLength(objB)) return false; //判斷長度是否一致
return CompareObj(objA, objB, true);//默認(rèn)為true
}
function CompareObj(objA, objB, flag) {
for (var key in objA) {
if (!flag) //跳出整個循環(huán)
break;
if (!objB.hasOwnProperty(key)) { flag = false; break; }
if (!isArray(objA[key])) { //子級不是數(shù)組時,比較屬性值
if (objB[key] != objA[key]) { flag = false; break; }
} else {
if (!isArray(objB[key])) { flag = false; break; }
var oA = objA[key], oB = objB[key];
if (oA.length != oB.length) { flag = false; break; }
for (var k in oA) {
if (!flag) //這里跳出循環(huán)是為了不讓遞歸繼續(xù)
break;
flag = CompareObj(oA[k], oB[k], flag);
}
}
}
return flag;
}
4.調(diào)用方法
var result = Compare(jsonObjA, jsonObjB);
console.log(result); // true or false