共计 537 个字符,预计需要花费 2 分钟才能阅读完成。
文中还应用了 sort 函数来排序,这样做的益处是只管对象程序不统一也能够比拟相等
let obj = {
leftDom1: 'rightDom1',
leftDom2: 'rightDom1',
leftDom3: 'rightDom3',
leftDom4: 'rightDom2',
};
let obj2 = {
leftDom2: 'rightDom1',
leftDom3: 'rightDom3',
leftDom4: 'rightDom2',
leftDom1: 'rightDom1',
};
function compareObjects(obj1, obj2) {const keys1 = Object.keys(obj1).sort();
const keys2 = Object.keys(obj2).sort();
if (keys1.length !== keys2.length) {return false;}
for (let i = 0; i < keys1.length; i++) {if (keys1[i] !== keys2[i] || obj1[keys1[i]] !== obj2[keys2[i]]) {return false;}
}
return true;
}
console.log(compareObjects(obj, obj2)); // true
正文完
发表至: javascript
2023-03-10