问题(来自 Eloquent Javascript 第二版,第 4 章,练习 4):
编写一个函数 deepEqual,它接受两个值,并且仅当它们相等时才返回 true
是相同的值或具有相同属性的对象,其值也是
与对 deepEqual 的递归调用相比,等于。
测试用例:
var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
My code:
var deepEqual = function (x, y) {
if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop))
return deepEqual(x[prop], y[prop]);
/*This is most likely where my error is. The question states that all the values
should be checked via recursion; however, with the current setup, only the first
set of properties will be checked. It passes the test cases, but I would like
to solve the problem correctly!*/
}
}
else if (x !== y)
return false;
else
return true;
}
我想我已经有了总体思路;但是,正如我在评论中所述,程序不会检查对象中的第二个属性。我觉得我有结构/逻辑问题,只是以错误的方式使用递归,因为我最初打算循环遍历属性,使用递归来比较第一个属性的值,然后继续循环到下一个属性属性并再次比较。虽然,我不确定这是否可能?
我已经进行了大量的思考并尝试了几种不同的方法,但这是迄今为止我得到的最正确的答案。有什么可能的提示可以为我指明正确的方向吗?