gpt4 book ai didi

javascript - 比较两个对象的值

转载 作者:行者123 更新时间:2023-11-29 20:43:06 25 4
gpt4 key购买 nike

<分区>

比较 2 个对象,只有当两个值相同时才返回 true。如果它们是两个以上相同的值或全部或全部返回 false。示例:

A = {a: 1, b: 2, c: 3};
B = {a: 1, b: 5, c: 7};
C = {a: 1, b: 2, c: 7};

A 和 B 应该返回 true,因为 A.a 和 B.a 相同。A 和 C 应该返回 false,因为 A.a 和 C.a 以及 A.b 和 C.b 相同。

到目前为止我有这个功能:

Link

但在这种情况下,const ObB7 返回 true,应该为 false。

这个功能可以简化吗?

function compareTwoObjects(ObA, ObB) {
const { a, b, c } = ObA;
const { a:d, b:e, c:f } = ObB;

if (
((a === d && (a !== e && a !== f))
|| (a === e && (a !== d && a !== f))
|| (a === f && (a !== e && a !== d)))

|| ((b === d && (b !== e && b !== f))
|| (b === e && (b !== d && b !== f))
|| (b === f && (b !== e && b !== d)))

|| ((c === d && (c !== e && c !== f))
|| (c === e && (c !== d && c !== f))
|| (c === f && (c !== e && c !== d)))
) {
return true;
}
return false;
}


const ObA = {a: 1, b: 2, c: 3};

const ObB0 = {a: 4, b: 5, c: 6}; // false
const ObB1 = {a: 4, b: 4, c: 4}; // false
const ObB2 = {a: 1, b: 1, c: 1}; // false
const ObB3 = {a: 2, b: 2, c: 2}; // false
const ObB4 = {a: 3, b: 3, c: 3}; // false
const ObB5 = {a: 1, b: 1, c: 7}; // false
const ObB6 = {a: 7, b: 2, c: 2}; // false
const ObB7 = {a: 7, b: 3, c: 3}; // false
const ObB8 = {a: 2, b: 3, c: 4}; // Should be false
const ObB9 = {a: 3, b: 7, c: 3}; // false

const ObB10 = {a: 5, b: 2, c: 3}; // true
const ObB11 = {a: 1, b: 5, c: 6}; // true
const ObB12 = {a: 0, b: 5, c: 3}; // true

console.log(compareTwoObjects(ObA, ObB0));
console.log(compareTwoObjects(ObA, ObB1));
console.log(compareTwoObjects(ObA, ObB2));
console.log(compareTwoObjects(ObA, ObB3));
console.log(compareTwoObjects(ObA, ObB4));
console.log(compareTwoObjects(ObA, ObB5));
console.log(compareTwoObjects(ObA, ObB6));
console.log(compareTwoObjects(ObA, ObB7));
console.log(compareTwoObjects(ObA, ObB8));
console.log(compareTwoObjects(ObA, ObB9));
console.log(compareTwoObjects(ObA, ObB10));
console.log(compareTwoObjects(ObA, ObB11));
console.log(compareTwoObjects(ObA, ObB12));

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