JavaScript判断变量是否为空

来源:互联网 发布:易语言qq盗号源码 编辑:程序博客网 时间:2024/04/28 04:08

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()              //trueisEmpty([])            //trueisEmpty({})            //trueisEmpty(0)             //trueisEmpty(Number("abc")) //trueisEmpty("")            //trueisEmpty("   ")         //trueisEmpty(false)         //trueisEmpty(null)          //trueisEmpty(undefined)     //true

参考:

http://blog.csdn.net/mycwq/article/details/17791633





7 0
原创粉丝点击