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.

64 lines
1.7 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

export const checkEmpty = (value) => {
// 处理 null 和 undefined
if (value === null || value === undefined) return true;
// 处理字符串
if (typeof value === 'string') {
return value.trim() === '';
}
// 处理数组
if (Array.isArray(value)) {
return value.length === 0;
}
// 处理对象
if (typeof value === 'object') {
return Object.keys(value).length === 0;
}
// 处理数字 - 0 不为空
if (typeof value === 'number') {
return false;
}
// 处理布尔值 - false 不为空
if (typeof value === 'boolean') {
return false;
}
// 其他类型默认为非空
return false;
};
// 递归函数转换字符串为数字(只转换看起来是数字的字符串)
export const convertNumericStrings = (obj) => {
Object.keys(obj).forEach(key => {
const value = obj[key];
// 如果是对象或数组,递归
if (typeof value === 'object' && value !== null) {
convertNumericStrings(value);
} else {
if (isNumberOrDecimal(value)) {
// 如果是数字或小数,直接转换
obj[key] = parseFloat(value);
}
}
// 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);
}