返回功能不起作用

时间:2015-03-26 21:42:42

标签: javascript function loops return javascript-objects

我编写了一个函数来比较两个对象是否相等。 为什么循环中的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}));
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

您对deepEqual的递归调用没有做任何事情。

您可以检查其结果,如果没有匹配则返回false:

&#13;
&#13;
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
&#13;
&#13;
&#13;

答案 1 :(得分:3)

您正在使用递归但不检查递归调用是否失败。试试这个:

    if (!deepEqual(a[aProp[i]], b[bProp[i]])) {
        return false;
    }