码迷,mamicode.com
首页 > 编程语言 > 详细

javascript判断变量是不是空值

时间:2016-11-12 01:35:26      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:return   cti   ace   http   []   style   bit   false   scn   

JavaScript本身没有判断一个变量是不是空值的函数,因为变量有可能是string,object,number,boolean等类型,类型不同,判断方法也不同。所以在文章中写了一个函数,用以判断JS变量是否空值,如果是undefined, null, ‘‘, NaN,false,0,[],{} ,空白字符串,都返回true,否则返回false

方法:

function isEmpty(v) {
    switch (typeof v) {
    case ‘undefined‘:
        return true;
    case ‘string‘:
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, ‘‘).length == 0) return true;
        break;
    case ‘boolean‘:
        if (!v) return true;
        break;
    case ‘number‘:
        if (0 === v || isNaN(v)) return true;
        break;
    case ‘object‘:
        if (null === v || v.length === 0) return true;
        for (var i in v) {
            return false;
        }
        return true;
    }
    return false;
}

测试:

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

转载:http://www.bitscn.com/school/Javascript/201503/463294.html

javascript判断变量是不是空值

标签:return   cti   ace   http   []   style   bit   false   scn   

原文地址:http://www.cnblogs.com/weishuanbao/p/6055896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!