比较对象
2024年04月09日
一、地址
根据引用地址来比较两个对象是否相同
二、属性
根据属性值来比较两个对象是否相同
2.1 Vue
2.2 Lodash
2.3 Simulation
function isObject(value) {
return typeof value === 'object' && value !== null;
}
function isEqual(value, other) {
if (!isObject(value) || !isObject(other)) {
return value === other;
}
const valueKeys = Object.keys(value);
const otherKeys = Object.keys(other);
if (valueKeys.length !== otherKeys.length) {
return false;
}
for (let key in value) {
if (!isEqual(value[key], other[key])) {
return false;
}
}
return true;
}
测试代码
const object = { a: 1 };
const other = { a: 1 };
console.log(isEqual(object, other));
三、比较 State
3.1 React
3.2 Vue2.0
3.3 Vue3.0
function hasChanged(prevValue, nextValue) {
if (prevValue === nextValue) {
return prevValue !== 0 && 1 / prevValue === 1 / nextValue;
} else {
return prevValue !== prevValue && nextValue !== nextValue;
}
}
测试用例
console.log('hasChanged', hasChanged(NaN, NaN));
console.log('Object.is', Object.is(NaN, NaN));
console.log('===', -0 === +0);
console.log('hasChanged', hasChanged(-0, +0));
console.log('Object.is', Object.is(-0, +0));
四、比较 Props
4.1 React
4.2 Vue2.0
4.3 Vue3.0
function hasPropsChanged(prevProps, nextProps) {
const nextKeys = Object.keys(nextProps);
if (nextKeys.length !== Object.keys(prevProps).length) {
return true;
}
for (let i = 0; i < nextKeys.length; i++) {
const key = nextKeys[i];
if (nextProps[key] !== prevProps[key]) {
return true;
}
}
return false;
}
测试用例
const prevProps = {
a: 3
};
const nextProps = {
a: 3
};
const result = hasPropsChanged(prevProps, nextProps);
console.log(result);