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

前端 未结 30 3564
眼角桃花
眼角桃花 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:11

    A solution I like a lot:

    Let's define that a blank variable is null, or undefined, or if it has length, it is zero, or if it is an object, it has no keys:

    function isEmpty (value) {
      return (
        // null or undefined
        (value == null) ||
    
        // has length and it's zero
        (value.hasOwnProperty('length') && value.length === 0) ||
    
        // is an Object and has no keys
        (value.constructor === Object && Object.keys(value).length === 0)
      )
    }
    

    Returns:

    • true: undefined, null, "", [], {}
    • false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }

提交回复
热议问题