How can I determine if a variable is 'undefined' or 'null'?

前端 未结 30 2183
耶瑟儿~
耶瑟儿~ 2020-11-22 03:30

How do I determine if variable is undefined or null?

My code is as follows:

var EmpN         


        
30条回答
  •  天命终不由人
    2020-11-22 04:17

    I've come to write my own function for this. JavaScript is weird.

    It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.

    function empty(v) {
        let type = typeof v;
        if (type === 'undefined') {
            return true;
        }
        if (type === 'boolean') {
            return !v;
        }
        if (v === null) {
            return true;
        }
        if (v === undefined) {
            return true;
        }
        if (v instanceof Array) {
            if (v.length < 1) {
                return true;
            }
        } else if (type === 'string') {
            if (v.length < 1) {
                return true;
            }
            if (v === '0') {
                return true;
            }
        } else if (type === 'object') {
            if (Object.keys(v).length < 1) {
                return true;
            }
        } else if (type === 'number') {
            if (v === 0) {
                return true;
            }
        }
        return false;
    }
    

    TypeScript-compatible.


    This function should do exactly the same thing like PHP's empty() function (see RETURN VALUES)

    Considers undefined, null, false, 0, 0.0, "0" {}, [] as empty.

    "0.0", NaN, " ", true are considered non-empty.

提交回复
热议问题