您的位置:首页 > Web前端 > JavaScript

JS 如何判断两个对象相等

2017-10-30 21:12 549 查看
摘抄自大神博客:https://github.com/mqyqingfeng/Blog/issues/41

前提条件:

1、NaN 和 NaN 相等

2、[1, 2] 和 [1, 2] 相等

3、{value: 1} 和 {value: 1} 相等

4、1 和 new Number(1) 相等

5、’Curly’ 和 new String(‘Curly’) 相等

6、true 和 new Boolean(true) 相等

下面我们来一步一步的讨论

+0 & -0

在很多情况下,+0 -0都是相等的:

// 表现1
console.log(+0 === -0); // true

// 表现2
(-0).toString() // '0'
(+0).toString() // '0'

// 表现3
-0 < +0 // false
+0 < -0 // false


但是,其实两者依旧能够体现出差异:

1 / +0 // Infinity
1 / -0 // -Infinity

1 / +0 === 1 / -0 // false


根据上面的这些特点,我们可以这样区分+0 -0

function eq(a, b){
if (a === b) return a !== 0 || 1 / a === 1 / b;
return false;
}

console.log(eq(0, 0)) // true
console.log(eq(0, -0)) // false


最后,解释一下为什么会有+0 -0之分:

这是因为 JavaScript 采用了IEEE_754 浮点数表示法(几乎所有现代编程语言所采用),这是一种二进制表示法,按照这个标准,最高位是符号位(0 代表正,1 代表负),剩下的用于表示大小。而对于零这个边界值 ,1000(-0) 和 0000(0)都是表示 0 ,这才有了正负零的区别。

NaN

我们希望,当比对NaN和NaN的时候,函数认为它们是相等的。

利用NaN不等于自身的特性,我们可以这样写:

function eq(a, b) {
if (a !== a) return b !== b;
}

console.log(eq(NaN, NaN)); // true


比对简单类型

// eq 第一版
// 用来过滤掉简单的类型比较,复杂的对象使用 deepEq 函数进行处理
function eq(a, b) {

// === 结果为 true 的区别出 +0 和 -0
if (a === b) return a !== 0 || 1 / a === 1 / b;

// typeof null 的结果为 object ,这里做判断,是为了让有 null 的情况尽早退出函数
if (a == null || b == null) return false;

// 判断 NaN
if (a !== a) return b !== b;

// 判断参数 a 类型,如果是基本类型,在这里可以直接返回 false
var type = typeof a;
if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;

// 更复杂的对象使用 deepEq 函数进行深度比较
return deepEq(a, b);
};


String基本类型和String对象

‘Cat’ 和 new String(‘Cat’) 的类型都不一样的:

console.log(typeof 'Cat'); // string
console.log(typeof new String('Cat')); // object


但是我希望它们在比对的时候是相等的!

他喵的…..怎么办呢?

而且神奇的是,使用Object.prototype.toString方法对两者做处理,两者的结果却是一致的!

var toString = Object.prototype.toString;
toString.call('Cat'); // "[object String]"
toString.call(new String('Cat')); // "[object String]"


我晕,神奇…..

解决方案是使用隐式类型转换:

console.log('Curly' + '' === new String('Curly') + ''); // true


于是,解决方案就是:

如果 a 和 b 的 Object.prototype.toString的结果一致,并且都是”[object String]”,那我们就使用 ” + a === ” + b 进行判断。

下面我们来讨论除了String其他对象的解决方案。

更多对象

其他对象例如Boolean, Date, RegExp,都可以借鉴String的方法,利用隐式类型转换。

var a = true;
var b = new Boolean(true);
console.log(+a === +b) // true

var a = new Date(2009, 9, 25);
var b = new Date(2009, 9, 25);
// date这个也加+号判断简直神奇了,然而亲测有效!
console.log(+a === +b) // true

var a = /a/i;
var b = new RegExp(/a/i);
// RegExp这个则利用的是转化为String
console.log('' + a === '' + b) // true


关于Number,稍微有点复杂,毕竟人家有个NaN

var a = Number(NaN);
var b = Number(NaN);

function eq() {
// 判断 Number(NaN) Object(NaN) 等情况
if (+a !== +a) return +b !== +b;
// 其他判断 ...
}

console.log(eq(a, b)); // true


这段代码上面出现过类似的是吧~

综合一下上面的内容

var toString = Object.prototype.toString;

function deepEq(a, b) {
var className = toString.call(a); // 注意这里必须要用call!不能直接调用,否则会返回[object Object]
if (className !== toString.call(b)) return false;

switch (className) {
case '[object RegExp]':
case '[object String]':
return '' + a === '' + b;
case '[object Number]':
if (+a !== +a) return +b !== +b;
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
return +a === +b;
}
// 其他判断
}


数组相等

数组和对象的判断其实很简单,就是循环遍历。但是这里只是单层的数组和对象

function deepEq(a, b) {
// 再接着上面的内容
if (areArrays) {

length = a.length;
if (length !== b.length) return false;

while (length--) {
if (!eq(a[length], b[length])) return false;
}
}
else {

var keys = Object.keys(a), key;
length = keys.length;

if (Object.keys(b).length !== length) return false;

while (length--) {
key = keys[length];
if (!(b.hasOwnProperty(key) && eq(a[key], b[key]))) return false;
}
}
return true;

}


逆天的循环引用

a = {foo: {b: {foo: {c: {foo: null}}}}};
b = {foo: {b: {foo: {c: {foo: null}}}}};
a.foo.b.foo.c.foo = a;
b.foo.b.foo.c.foo = b;
// 晕


如果还按照原来的逻辑,那么,就是死循环…..

解决问题的方法是借用了两个stack(也就是数组啦)

var a, b;

a = { foo: { b: { foo: { c: { foo: null } } } } };
b = { foo: { b: { foo: { c: { foo: null } } } } };
a.foo.b.foo.c.foo = a;
b.foo.b.foo.c.foo = b;

function eq(a, b, aStack, bStack) {
if (typeof a == 'number') {
return a === b;
}

return deepEq(a, b, aStack, bStack)
}

function deepEq(a, b, aStack, bStack) {

aStack = aStack || [];
bStack = bStack || [];

var length = aStack.length;
// 数组的解决方案
while (length--) { // 遍历,找出是否存在循环引用
if (aStack[length] === a) {
return bStack[length] === b;
}
}

aStack.push(a);
bStack.push(b);

// 对象的解决方案
var keys = Object.keys(a);
var length = keys.length;
var key;

while (length--) {
key = keys[length]

console.log(a[key], b[key], aStack, bStack)

if (!eq(a[key], b[key], aStack, bStack)) return false;
// 递归调用,push了a,b到stack中用来排除循环引用。
}

aStack.pop();
bStack.pop();
return true;

}

console.log(eq(a, b))


终于完成了,下面来一版完整的代码:

var toString = Object.prototype.toString;

function isFunction(obj) {
return toString.call(obj) === '[object Function]'
}

function eq(a, b, aStack, bStack) {

// === 结果为 true 的区别出 +0 和 -0
if (a === b) return a !== 0 || 1 / a === 1 / b;

// typeof null 的结果为 object ,这里做判断,是为了让有 null 的情况尽早退出函数
if (a == null || b == null) return false;

// 判断 NaN
if (a !== a) return b !== b;

// 判断参数 a 类型,如果是基本类型,在这里可以直接返回 false
var type = typeof a;
if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;

// 更复杂的对象使用 deepEq 函数进行深度比较
return deepEq(a, b, aStack, bStack);
};

function deepEq(a, b, aStack, bStack) {

// a 和 b 的内部属性 [[class]] 相同时 返回 true
var className = toString.call(a);
if (className !== toString.call(b)) return false;

switch (className) {
case '[object RegExp]':
case '[object String]':
return '' + a === '' + b;
case '[object Number]':
if (+a !== +a) return +b !== +b;
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
return +a === +b;
}

var areArrays = className === '[object Array]';
// 不是数组
if (!areArrays) {
// 过滤掉两个函数的情况
if (typeof a != 'object' || typeof b != 'object') return false;

var aCtor = a.constructor,
bCtor = b.constructor;
// aCtor 和 bCtor 必须都存在并且都不是 Object 构造函数的情况下,aCtor 不等于 bCtor, 那这两个对象就真的不相等啦
if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) {
return false;
}
}

aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;

// 检查是否有循环引用的部分
while (length--) {
if (aStack[length] === a) {
return bStack[length] === b;
}
}

aStack.push(a);
bStack.push(b);

// 数组判断
if (areArrays) {

length = a.length;
if (length !== b.length) return false;

while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
}
// 对象判断
else {

var keys = Object.keys(a),
key;
length = keys.length;

if (Object.keys(b).length !== length) return false;
while (length--) {

key = keys[length];
if (!(b.hasOwnProperty(key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}

aStack.pop();
bStack.pop();
return true;

}

console.log(eq(0, 0)) // true
console.log(eq(0, -0)) // false

console.log(eq(NaN, NaN)); // true
console.log(eq(Number(NaN), Number(NaN))); // true

console.log(eq('Curly', new String('Curly'))); // true

console.log(eq([1], [1])); // true
console.log(eq({ value: 1 }, { value: 1 })); // true

var a, b;

a = { foo: { b: { foo: { c: { foo: null } } } } };
b = { foo: { b: { foo: { c: { foo: null } } } } };
a.foo.b.foo.c.foo = a;
b.foo.b.foo.c.foo = b;

console.log(eq(a, b)) // true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript