实现一个深度比较
Posted 悠悠洛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现一个深度比较相关的知识,希望对你有一定的参考价值。
function compare(a, b) {
const typeA = {}.toString.call(a);
const typeB = {}.toString.call(b);
if (typeA !== typeB) return false;
let result = false;
switch (typeA) {
case ‘[object Undefined]‘:
case ‘[object Null]‘:
result = true;
break;
case ‘[object String]‘:
case ‘[object Number]‘:
if (a === b) result = true;
break;
case ‘[object Array]‘:
if (a.length === b.length) {
result = a.every(aitem => b.some(bitem => compare(aitem, bitem)));
}
break;
case ‘[object Object]‘:
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length === keysB.length) {
result = keysA.every((key) => {
if (b.hasOwnProperty(key)) {
return compare(a[key], b[key]);
}
return false;
});
}
break;
}
return result;
}
export default function deepCompare(a, b) {
return compare(a, b);
}
以上是关于实现一个深度比较的主要内容,如果未能解决你的问题,请参考以下文章