JavaScript判断变量是否为空的自定义函数分享

  作者:bea

JavaScript本身没有判断一个变量是不是空值的函数,因为变量有可能是string,object,number,boolean等类型,类型不同,判断方法也不同。所以在文章中写了一个函数,用以判断JS变量是否空值,如果是undefined, null, '', NaN,false,0,[],{} ,空白字符串,都返回true,否则返回false 代码如下: function isEmpty(v) { switch (typeof v) { case 'unde
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(/(^[
]*)|([
]*$)/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






有用  |  无用

猜你喜欢