问题(来自《JavaScript编程精解》第2版第4章练习4):
编写一个名为deepEqual的函数,该函数接受两个值,并仅在它们是相同值或具有相同属性且这些属性的值与对deepEqual的递归调用进行比较时也相等的对象时返回true。
测试用例:
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
我的代码:
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;
}
我觉得我大致明白了;但是,正如我在评论中所说的那样,程序将不会检查对象中的第二个属性。我感觉存在结构/逻辑问题,并且仅仅是以错误的方式使用递归,因为我最初的想法是循环遍历属性,使用递归来比较第一个属性的值,然后继续在循环中进行下一个属性的比较。虽然,我不确定是否可能实现?
我已经仔细考虑过并尝试了几种不同的方法,但这是迄今为止我得出的最正确的答案。有任何可能的提示可以指引我朝着正确的方向吗?
.hasOwnProperty()
检查,或者更好的是使用已经通过调用Object.keys()
获得的返回值来进行迭代,因为这些返回值已经被限制为“自有”属性。 - Pointy0, 1, 2...
的对象。for... in
循环遍历这些“键”并比较值(在本例中是数组中的整数)。没有必要 - 也没有明智的方法 - 以不同的方式处理数组。示例:https://codepen.io/paulroub/pen/NWxvprK?editors=0011 - Paul Roub