JavaScript判断变量是否为空的自定义函数分享
JavaScript本身没有判断一个变量是不是空值的函数,因为变量有可能是string,object,number,boolean等类型,类型不同,判断方法也不同。所以在文章中写了一个函数,用以判断JS变量是否空值,如果是undefined,null,'',NaN,false,0,[],{},空白字符串,都返回true,否则返回false
functionisEmpty(v){
switch(typeofv){
case'undefined':
returntrue;
case'string':
if(v.replace(/(^[\t\n\r]*)|([\t\n\r]*$)/g,'').length==0)returntrue;
break;
case'boolean':
if(!v)returntrue;
break;
case'number':
if(0===v||isNaN(v))returntrue;
break;
case'object':
if(null===v||v.length===0)returntrue;
for(variinv){
returnfalse;
}
returntrue;
}
returnfalse;
}
测试:
isEmpty() //true
isEmpty([]) //true
isEmpty({}) //true
isEmpty(0) //true
isEmpty(Number("abc"))//true
isEmpty("") //true
isEmpty(" ") //true
isEmpty(false) //true
isEmpty(null) //true
isEmpty(undefined) //true
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语