场景:
前端的一种交互场景,当前编辑页,页面是否有修改,有修改离开页面需二次弹框提示,是否未保存离开!
本质: 判断两个数据是否完全相等
ps: 可能存在极端未涉及到的情况(欢迎大佬们补充)
代码:
// 通用判断两个对象(/数字/字符串/Date/数据/对象)是否相等 false 不相等
// 使用方法 js文件定义方法,默认导出 publicCheckDiff(数据1, 数据2, 参数3)
// 重要!!! 参数3是判断场景 数组数据是否要sort排序 true 需要排序
const checkType = data => {
let type = '';
if (data instanceof Array) {
type = 'Array';
}
else if (data instanceof Date) {
type = 'Date';
}
else if (data instanceof Object) {
type = 'Object';
}
return type;
};
const publicCheckDiff = (data1, data2, sort = false) => {
const simpleType1 = typeof data1;
const simpleType2 = typeof data2;
if (simpleType1 !== simpleType2) {
return false;
}
if (simpleType1 === simpleType2) {
if (simpleType1 !== 'object' && simpleType2 !== 'object' && data1 !== data2) {
return false;
}
const complexType1 = checkType(data1);
const complexType2 = checkType(data2);
if (complexType1 !== complexType2) {
return false;
}
if (complexType1 === 'Array') {
if (data1.length !== data2.length) {
return false;
}
// 这里针对数组要不要 sort排序
if (sort) {
data1 = data1.sort();
data2 = data2.sort();
}
for (let i = 0; i < data1.length; i++) {
if (typeof data1[i] === 'object' || typeof data2[i] === 'object') {
const res = publicCheckDiff(data1[i], data2[i]);
if (!res) {
return false;
}
}
else if (data1[i] !== data2[i]) {
return false;
}
}
}
if (complexType1 === 'Date' || complexType2 === 'Date') {
if (new Date(data1)?.getTime() !== new Date(data2)?.getTime()) {
return false;
}
}
if (complexType1 === 'Object') {
const props1 = Object.keys(data1);
const props2 = Object.keys(data2);
if (props1.length !== props2.length) {
return false;
}
for (let i = 0; i < props1.length; i++) {
const propName = props1[i];
if (typeof data1[propName] === 'object' || typeof data2[propName] === 'object') {
const res = publicCheckDiff(data1[propName], data2[propName]);
if (!res) {
return false;
}
}
else if (data1[propName] !== data2[propName]) {
return false;
}
}
}
}
return true;
};
export default publicCheckDiff;