在js中空数组([]),空对象({})会也会被判断为真,故封装一个[]、{}为假的一个方法来判断数据真假。
function isNotEmpty(data) {
// 对于数组,检查其长度
if (Array.isArray(data)) {
return data.length > 0;
}
// 对于对象,检查其属性个数
if (typeof data === 'object') {
return Object.keys(data).length > 0;
}
// 对于其他类型(如字符串、数字等),检查是否为非空值
return Boolean(data); // 对于非空字符串、非零数字等,返回 true
}
console.log(isNotEmpty({})); // false
console.log(isNotEmpty([])); // false
console.log(isNotEmpty([1, 2])); // true
console.log(isNotEmpty({a: 1})); // true
console.log(isNotEmpty(null)); // false
console.log(isNotEmpty(42)); // true
console.log(isNotEmpty('Hello')); // true
console.log(isNotEmpty('')); // false
判断是否为数组,是数组则判断数组是否为空。
isArrayValid(data) {
if (Array.isArray(data)) {
return value.length > 0;
}
return false;
}