xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js one object equal to another object checker All In One

js one object equal to another object checker All In One

js 判断两个对象是否相等

  1. 对象是引用类型,比较的是引用地址是否相等

  2. Primitive values 是原始类型,比较的是值是否相等

JavaScript types

The set of types in the JavaScript language consists of primitive values and objects.

  1. Primitive values (immutable datum represented directly at the lowest level of the language)

Boolean type
Null type
Undefined type
Number type
BigInt type (ES6+)
String type
Symbol type (ES6)

  1. Objects (collections of properties)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

Equality Comparison

JavaScript provides three different value-comparison operations:

=== - Strict Equality Comparison ("strict equality", "identity", "triple equals")

== - Abstract Equality Comparison ("loose equality", "double equals")

Object.is provides SameValue (new in ES2015).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Object.is & ===


const obj1 = {o: {b: {j: {value: 1}}}};
// {o: {…}}o: b: j: {value: 1}[[Prototype]]: Object[[Prototype]]: Object[[Prototype]]: Object

const obj2 = {o: {b: {j: {value: 2}}}};
// {o: {…}}

const obj = obj1;
// {o: {…}}

obj1 === obj1;
// true
obj1 === obj2;
// false
obj1 === obj;
// true


Object.is(obj1, obj2);
// false
Object.is(obj1, obj);
// true

const temp = {o: {b: {j: {value: 1}}}};

obj1 === temp;
// false

Object.is(obj1, temp);
// false

比较对象所有属性是否相等

const obj1 = {o: {b: {j: {value: 1}}}};
// {o: {…}}o: b: j: {value: 1}[[Prototype]]: Object[[Prototype]]: Object[[Prototype]]: Object

const obj2 = {o: {b: {j: {value: 2}}}};
// {o: {…}}

const obj = obj1;
// {o: {…}}

Object.is(JSON.stringify(obj1), JSON.stringify(obj2));
// false

Object.is(JSON.stringify(obj1), JSON.stringify(obj));
// true

// ✅
const temp = {o: {b: {j: {value: 1}}}};

Object.is(JSON.stringify(obj1), JSON.stringify(temp));
// true  


  1. 手动实现,递归判断 👎

没必要, waste of time (life is short I need python)

// life is short I don't need that at all!
// 人生苦短,我根本不需要!

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-16 11:03  xgqfrms  阅读(35)  评论(3编辑  收藏  举报