Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 4263
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  佛祖请我去吃肉
    2020-11-22 00:05

    function isEmpty(obj) {
        if (typeof obj == 'number') return false;
        else if (typeof obj == 'string') return obj.length == 0;
        else if (Array.isArray(obj)) return obj.length == 0;
        else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
        else if (typeof obj == 'boolean') return false;
        else return !obj;
    }
    

    In ES6 with trim to handle whitespace strings:

    const isEmpty = value => {
        if (typeof value === 'number') return false
        else if (typeof value === 'string') return value.trim().length === 0
        else if (Array.isArray(value)) return value.length === 0
        else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
        else if (typeof value === 'boolean') return false
        else return !value
    }
    

提交回复
热议问题