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 红包祝福语简短10字
18 周六早晨祝福语简短