You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.8 KiB
JavaScript

1 month ago
export const checkEmpty=(value)=>{
// 处理 null 和 undefined
1 month ago
if (value === null || value === undefined) return true;
1 month ago
1 month ago
// 处理字符串
if (typeof value === 'string') {
return value.trim() === '';
}
1 month ago
1 month ago
// 处理数组
if (Array.isArray(value)) {
return value.length === 0;
}
1 month ago
1 month ago
// 处理对象
if (typeof value === 'object') {
return Object.keys(value).length === 0;
}
1 month ago
1 month ago
// 处理数字 - 0 不为空
if (typeof value === 'number') {
return false;
}
1 month ago
1 month ago
// 处理布尔值 - false 不为空
if (typeof value === 'boolean') {
return false;
}
1 month ago
1 month ago
// 其他类型默认为非空
return false;
};
// 递归函数转换字符串为数字(只转换看起来是数字的字符串)
1 month ago
export const convertNumericStrings = (obj)=> {
1 month ago
Object.keys(obj).forEach(key => {
1 month ago
1 month ago
const value = obj[key];
1 month ago
// console.log(`Processing key: ${key}`,'=',value); // 调试输出
1 month ago
// 如果是对象或数组,递归
if (typeof value === 'object' && value !== null) {
convertNumericStrings(value);
} else {
1 month ago
if(isNumberOrDecimal(value)){
// 如果是数字或小数,直接转换
obj[key] = parseFloat(value);
}
1 month ago
}
// if (typeof value === 'string') {
// // 尝试转换为数字
// const num = parseFloat(value);
// // 检查转换是否有效并且原字符串去掉空格后等于转换后的数字字符串避免将非数字字符串转换为NaN
// if (!isNaN(num) && value.trim() === num.toString()) {
// obj[key] = num;
// }
// // 如果还有其他格式的字符串数字,可以调整上面的条件
// }
});
return obj;
}
function isNumberOrDecimal(str) {
const regexDecimal = /^\d+(\.\d+)?$/;
return regexDecimal.test(str);
}