const isBasicType = (t: any) => {标签:const,函数,js,key,shallowEqual,return,false,any From: https://www.cnblogs.com/lhp2012/p/17128022.html
return t === "number" || t === "string" || t === "boolean" || t === 'undefined';
}
/**
* 数组和对象都能比较
* @param a
* @param b
* @returns {boolean}
*/
function compareByObject(a:any,b:any){
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
return false;
}
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b);
for (let idx = 0; idx < keysA.length; idx++) {
const key = keysA[idx];
if (!bHasOwnProperty(key) || a[key] !== b[key]) {
return false;
}
}
return true;
}
const shallowEqual = (a:any, b:any) => {
const aType = typeof a;
const bType = typeof b;
if (aType !== bType) {
return false;
}
if (isBasicType(aType) && isBasicType(bType)) {
return a === b;
}
if (typeof a !== "object" || !a || typeof b !== "object" || !b) {
return false;
}
if (a === b) {
return true;
}
return compareByObject(a,b);
};
export {
shallowEqual
}