I wrote a function which compares two objects whether the are equal. Why does my return statement in the loop not work?
var deepEqual = function(a, b){ var aProp = Object.getOwnPropertyNames(a); var bProp = Object.getOwnPropertyNames(b); if(aProp.length !== bProp.length){ return false; } else{ for (var i = 0; i < aProp.length; i++) { if(typeof a[aProp[i]] === 'object' && typeof b[bProp[i]] === 'object'){ deepEqual(a[aProp[i]], b[bProp[i]]); } else{ if(a[aProp[i]] !== b[bProp[i]]){ return false; // WHY IT DOESN'T WORK??? } } }; return true; } }; var obj = {a: 2, here: {is: "asn"}, object: 2, d: 12}; console.log(deepEqual(obj, {a: 2, here: {is: "an"}, object: 2, d: 12}));
You're not doing anything with the recursive call to deepEqual
.
You can check its result, and return false if there's no match:
var deepEqual = function(a, b){ var aProp = Object.getOwnPropertyNames(a); var bProp = Object.getOwnPropertyNames(b); if(aProp.length !== bProp.length){ return false; } else { for (var i = 0; i < aProp.length; i++) { if(typeof a[aProp[i]] === 'object' && typeof b[bProp[i]] === 'object'){ if(!deepEqual(a[aProp[i]], b[bProp[i]])) { //<- changed return false; } } else { if(a[aProp[i]] !== b[bProp[i]]){ return false; } } } return true; } }; var obj = {a: 2, here: {is: "asn"}, object: 2, d: 12}; console.log(deepEqual(obj, {a: 2, here: {is: "an"}, object: 2, d: 12})); //false
You're using recursion but not checking to see if a recursive call has failed. Try this instead:
if (!deepEqual(a[aProp[i]], b[bProp[i]])) {
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.