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

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

    Code on GitHub

    const isEmpty = value => (
      (!value && value !== 0 && value !== false)
      || (Array.isArray(value) && value.length === 0)
      || (isObject(value) && Object.keys(value).length === 0)
      || (typeof value.size === 'number' && value.size === 0)
    
      // `WeekMap.length` is supposed to exist!?
      || (typeof value.length === 'number'
          && typeof value !== 'function' && value.length === 0)
    );
    
    // Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
    const isObject = value =>
      Object.prototype.toString.call(value) === '[object Object]';
    

    Poor man's tests

提交回复
热议问题