js 如何比较两个对象相等

JavaScript015

js 如何比较两个对象相等,第1张

有两种方法,

把两个对象转换成json之后比较字符串是否相等JSON.stringify(Object)

获取两个对象的所有字段,然后再去比较Object.key(对象)

今天看红宝书,里面讲到相等操作符,也就是==和===

“如果两个操作数都是对象,则比较他们是不是同一个对象,如果两个操作数都指向同一个对象,则相等操作符返回true,否则,返回false”。

我做了一个例子

function person() {

// define some peroperty here

}

var p1 = new person()

var p2 = new person()

console.log(p1 == p2) //false

按照他说的指向同一个对象了啊,为什么返回的是false呢?

然后我又查了查,发现有人这样说

“如果等号两边是对象或者对象的函数,则比较地址是否相等(即判断两者是否引用的同一对象)”

可是这里的地址指什么呢?

然后 有综合了一些查询结果,发现这里的地址应该指的是内存地址。“每生成一个实例就会重新占用一些内存”,所以两次生成的person占用的是不同的内存地址。所以返回结果是false。

那这样的话怎么样才能用==返回true呢?我又查了一下,没有找到特别合适的例子,指找到一个用prototype定义函数可以得到== 返回true的效果

function person(name) {

this.name=name

}

var p1 = new person("p1")

var p2 = new person("p2")

console.log(p1 == p2) //false

person.prototype.sayHi = function() {

// do sayHi here

}

console.log(p1.sayHi() == p2.sayHi()) //true

console.log(p1.sayHi() === p2.sayHi()) //true

本js代码通过对js对象进行各方面的比较来判断两个对象是否相等

cmp = function( x, y ) {

// If both x and y are null or undefined and exactly the same

if ( x === y ) {

return true

}

// If they are not strictly equal, they both need to be Objects

if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {

return false

}

//They must have the exact same prototype chain,the closest we can do is

//test the constructor.

if ( x.constructor !== y.constructor ) {

return false

}

for ( var p in x ) {

//Inherited properties were tested using x.constructor === y.constructor

if ( x.hasOwnProperty( p ) ) {

// Allows comparing x[ p ] and y[ p ] when set to undefined

if ( ! y.hasOwnProperty( p ) ) {

return false

}

// If they have the same strict value or identity then they are equal

if ( x[ p ] === y[ p ] ) {

continue

}

// Numbers, Strings, Functions, Booleans must be strictly equal

if ( typeof( x[ p ] ) !== "object" ) {

return false

}

// Objects and Arrays must be tested recursively

if ( ! Object.equals( x[ p ], y[ p ] ) ) {

return false

}

}

}

for ( p in y ) {

// allows x[ p ] to be set to undefined

if ( y.hasOwnProperty( p ) &&! x.hasOwnProperty( p ) ) {

return false

}

}

return true

}

使用:

objA={

a:'123',

b:'456'

}

objB={

a:'123',

b:'000'

}

var isEqual= cmp(objA, objB)

console.log(isEqual) // false 不相同