hcy-tool-test2
Version:
一些常用工具
31 lines (26 loc) • 743 B
text/typescript
/**
* 是否为空
* @param {any} data
* @return {Boolean}
*/
export function isEmpty(data: any, stringEmpty = false): boolean {
if (data == null) {
// 使用 == 可以同时检查 null 和 undefined
return true;
}
// 如果启用了对空字符串的检查,并且数据是表示空对象、数组或 null/undefined 的字符串
if (stringEmpty && typeof data === "string") {
try {
data = JSON.parse(data); // 尝试解析字符串为实际值
} catch (e) {
// 解析失败则保持原样
}
}
if (Array.isArray(data)) {
return data.length === 0;
}
if (typeof data === "object") {
return Object.keys(data).length === 0;
}
return data === "";
}