1 引言
Object 类型的比较是非常重要的基础知识,通过 How to Compare Objects in JavaScript 这篇文章,我们可以学到四种对比方法:引用对比、手动对比、浅对比、深对比。
2 简介
引用对比
下面三种对比方式用于 Object,皆在引用相同是才返回 true
:
===
==
Object.is()
const hero1 = {
name: "Batman",
};
const hero2 = {
name: "Batman",
};
hero1 === hero1; // => true
hero1 === hero2; // => false
hero1 == hero1; // => true
hero1 == hero2; // => false
Object.is(hero1, hero1); // => true
Object.is(hero1, hero2); // => false
手动对比
写一个自定义函数,按照对象内容做自定义对比也是一种方案:
function isHeroEqual(object1, object2) {
return object1.name === object2.name;
}
const hero1 = {
name: "Batman",
};
const hero2 = {
name: