[英]Return in function doesn't work
I wrote a function which compares two objects whether the are equal. 我写了一个比较两个对象是否相等的函数。 Why does my return statement in the loop not work?
为什么循环中的return语句不起作用?
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
. 递归调用
deepEqual
并没有做任何事情。
You can check its result, and return false if there's no match: 您可以检查其结果,如果不匹配,则返回false:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.