gpt4 book ai didi

Javascript - deepEqual 比较

转载 作者:可可西里 更新时间:2023-11-01 02:14:11 26 4
gpt4 key购买 nike

问题(来自 Eloquent Javascript 第 2 版,第 4 章,练习 4):

Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to 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

我的代码:

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;
}

我想我已经掌握了总体思路;但是,就像我在评论中所说的那样,程序不会检查对象中的第二个属性。我觉得我有一个结构/逻辑问题并且只是以错误的方式使用递归,因为我最初打算循环遍历属性,使用递归比较第一个属性的值,然后继续循环到下一个属性并再次比较。虽然,我不确定这是否可能?

我已经进行了大量思考并尝试了几种不同的方法,但这是迄今为止我得出的最正确的答案。有什么提示可以指引我正确的方向吗?

最佳答案

如您所料,您正在返回所见第一个属性的匹配项。如果该属性不匹配,您应该返回 false,但继续查找其他情况。

此外,如果在 y 上找不到 prop 属性,则返回 false(即计数匹配,但实际属性不匹配) .

如果所有属性都匹配,返回true:

var deepEqual = function (x, y) {
if (x === y) {
return true;
}
else 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))
{
if (! deepEqual(x[prop], y[prop]))
return false;
}
else
return false;
}

return true;
}
else
return false;
}

var deepEqual = function (x, y) {
if (x === y) {
return true;
}
else 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))
{
if (! deepEqual(x[prop], y[prop]))
return false;
}
else
return false;
}

return true;
}
else
return false;
}

var obj = {here: {is: "an", other: "3"}, 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}));
// → false
console.log(deepEqual(obj, {here: {is: "an", other: "2"}, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an", other: "3"}, object: 2}));
// → true

关于Javascript - deepEqual 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25456013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com