JS判断两个对象内容是否相等

JavaScript012

JS判断两个对象内容是否相等,第1张

ES6有一个方法来判断两个对象是否相等

但是这个相等,和我们平时要的相等可能不一样

这个方法判断的是a和b是不是同一个指针的对象

比如说

但是下面这种情况就不管用了

当我们只需要两个对象的内容相同的时候,他就没效果了

思路

只要两个对象的名和键值都相同。那么两个对象的内容就相同了

1.用Object.getOwnPropertyNames拿到对象的所以键名数组

2.比对键名数组的长度是否相等。否=>false。真=>3

3.比对键名对应的键值是否相等

粗略一看没问题

但是细心的同学发现如果 键值也是对象的话

那这个方法就不管用了

这个时候递归一下就可以解决了

注意,递归的时候要判断prop是不是Object,然后会进入无限递归的死循环

有两种方法,

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

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

本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 不相同