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


本文向大家介绍JavaScript判断变量是否为空的自定义函数分享,包括了JavaScript判断变量是否为空的自定义函数分享的使用技巧和注意事项,需要的朋友参考一下

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