首先是最常用的表达式if(any)和if(!any),对于一般对象if(any)等价于if(any != null && any != undefined),if(!any)等价于if(any == null && any == undefined)
对于特定类型,或者说最常用的基本类型
- 如果是Number类型,等价于if(any != null && any != undefined && any != 0)
- 如果是String类型,等价于if(any != null && any != undefined && any != "")
- 如果是Boolean类型,等价于if(any != null && any != undefined && any != false)
所以能满足大部分的情况,但是对于空对象{}和空数组[]就无能为力了
我的思路是,如果是对象,就遍历它的key然后去判断长度如果为0就为{},当然也可以直接转成字符串然后和"{}"比较,
类似的,如果是数组,就判断它的length如果为0就为[],也可以直接转成字符串然后和"[]"比较,代码实现如下
const isEmpty = function(any){
if(any){
//数组必须放在对象之前判断,数组也是对象
if(any instanceof Array){
return any.length == 0;
}
//是对象类型的
if(any instanceof Object){
return Object.keys(any).length == 0;
}
return false;
}
//是基本类型中的空值
return true
}
测试代码如下
console.warn("isEmpty('')", isEmpty(''));
console.warn("isEmpty(0)", isEmpty(0));
console.warn("isEmpty(false)", isEmpty(false));
console.warn("isEmpty(null)", isEmpty(null));
console.warn("isEmpty(undefined)", isEmpty(undefined));
console.warn("isEmpty({})", isEmpty({}));
console.warn("isEmpty([])", isEmpty([]));
console.warn("isEmpty('123')", isEmpty('123'));
console.warn("isEmpty(10)", isEmpty(10));
console.warn("isEmpty(true)", isEmpty(true));
console.warn("isEmpty({a: 123})", isEmpty({a: 123}));
console.warn("isEmpty(['aaa'])", isEmpty(['aaa']));
Chrome浏览器运行结果