js判断两个对象的值是否相等

JavaScript020

js判断两个对象的值是否相等,第1张

判断对象相等的步骤:

1.先判断俩者是不是对象

2.是对象后俩者长度是否一致

3.判断俩个对象的所有key值是否相等相同

4.判断俩个对象的相应的key对应的值是否相同

来一个递归判断里面的对象循环1-4步骤代码如下:

diff(obj1,obj2){

console.log('obj12'+obj1,obj2)

var o1 = obj1 instanceof Object

var o2 = obj2 instanceof Object

if(!o1 || !o2){/* 判断不是对象 */

return obj1 === obj2

}

if(Object.keys(obj1).length !== Object.keys(obj2).length){

return false

}

for(var attr in obj1){

var t1 = obj1[attr] instanceof Object

var t2 = obj2[attr] instanceof Object

if(t1 &&t2){

return diff(obj1[attr],obj2[attr])

}else if(obj1[attr] !== obj2[attr]){

return false

}

}

return true

}

有两种方法,

把两个对象转换成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 不相同