引入
JS是个弱类型语言,不同类型的数据有不同的判空方式,于是我,我想着将 数字、对象、集合、字符串这几种类型的数据判空封装起来,实现如下效果
封装对应函数
/**
* 判断对象是否为空
* @param obj
* @returns
*/
function isEmpty(obj) {
// 数字判空
if (isNumber(obj)) {
return false;
}
// 字符串和数组判空
if (obj && obj.length > 0) {
return false;
}
// 按照对应的数据类型进行数据判空
let objType = Object.prototype.toString.call(obj);
// 字符串和数组判空
if (objType === '[object Array]' || objType === '[object String]') {
if (obj && obj.length > 0) {
return false;
}
}
// 如果是对象
if (objType === '[object Object]' && !(JSON.stringify(obj) == "{}")) {
return false;
}
return true;
}
/**
* 判断是否为数字
* @param obj
* @returns
*/
function isNumber(obj) {
if (parseFloat(obj).toString() == "NaN") {
return false;
}
return true;
}
对应的测试代码
console.log(isEmpty(""))
console.log(isEmpty({}))
console.log(isEmpty(4))
console.log(isEmpty(undefined))