我尝试使用递归进行深度对象比较,但我的函数返回 undefined
。
我知道有更好的方法来比较对象(IE JSON.Stringify()
),但我不明白为什么我的函数返回 undefined
。
function deepObjCompare(obj1, obj2) {
Object.keys(obj1).forEach((key) => {
const key1 = obj1[key];
const key2 = obj2[key];
if (key2) {
if (typeof key1 === "object" && key1 !== null) {
deepObjCompare(key1, key2);
} else if (key1 === key2) {
return true;
}
}
return false;
});
}
const obj1 = {
name: "Bill",
address: {
cityNow: "Paris",
cityFuture: "NYC"
},
age: 39
};
const obj2 = {
name: "Bill",
address: {
cityNow: "Paris",
cityFuture: "NYC"
},
age: 39
};
const obj3 = {
name: "Bob",
address: "Paris",
age: 39
};
console.log(deepObjCompare(obj1, obj3));
最佳答案
我在这里看到三个主要问题:
deepObjCompare
缺少返回语句,这就是它隐式返回undefined
的原因。.forEach
方法总是返回undefined
,因此您需要将其更改为另一个将返回实际值的方法。我认为.every
是您在这里所追求的。- 您不返回递归调用的结果。
总而言之,这会将您的代码段更改为以下内容:
function deepObjCompare(obj1, obj2) {
return Object.keys(obj1).every((key) => { // Use .every and return the result!
const key1 = obj1[key];
const key2 = obj2[key];
if (key2) {
if (typeof key1 === "object" && key1 !== null) {
return deepObjCompare(key1, key2); // Return the result of your recursive call!
} else if (key1 === key2) {
return true;
}
}
return false;
});
}
const obj1 = {
name: "Bill",
address: {
cityNow: "Paris",
cityFuture: "NYC"
},
age: 39
};
const obj2 = {
name: "Bill",
address: {
cityNow: "Paris",
cityFuture: "NYC"
},
age: 39
};
const obj3 = {
name: "Bob",
address: "Paris",
age: 39
};
console.log(deepObjCompare(obj1, obj3)); // false
console.log(deepObjCompare(obj1, obj2)); // true
关于javascript - 使用递归进行深度对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52523446/