export const notEmpty = (data) => {
const type = Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
switch (type) {
case 'null':
case 'undefined':
return false;
case 'object':
return Object.keys(data).length > 0;
case 'array':
case 'string':
return data !== 'undefined' && data !== 'null' && data.length > 0;
case 'boolean':
return !!data;
default:
return true;
}
};
我已经完成了上述功能,用于检查null,undefined,''和空Array和Object。但是正如您所看到的,它有很多假设。有没有更好的解决方案来检查它们?
您当前的功能看起来还不错,但是您可以像这样改善它:
const notEmpty = (data) => {
if (!data) return false;
if (typeof data === 'object') return Object.keys(data).length > 0;
return true;
};
console.log(notEmpty(null));
console.log(notEmpty(undefined));
console.log(notEmpty(''));
console.log(notEmpty({}));
console.log(notEmpty([]));
console.log(notEmpty(false));
console.log(notEmpty({ a: 1 }));
console.log(notEmpty(true));
console.log(notEmpty('abc'));
console.log(notEmpty([1, 2, 3]));
数组是对象,因此上面的内容也会检查数组。