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

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

    This will check if variable of indeterminate nesting is undefined

    function Undef(str) 
    {
      var ary = str.split('.');
      var w = window;
      for (i in ary) {
        try      { if (typeof(w = w[ary[i]]) === "undefined") return true; }
        catch(e) { return true; }
      }
      return false;
    }
    
    if (!Undef("google.translate.TranslateElement")) {
    

    The above checks if the Google translate function TranslateElement exists. This is equivalent to:

    if (!(typeof google === "undefined" 
     || typeof google.translate === "undefined" 
     || typeof google.translate.TranslateElement === "undefined")) {
    
    0 讨论(0)
  • 2020-11-22 00:04

    Take a look at the new ECMAScript Nullish coalescing operator

    You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.

    let x = foo ?? bar();
    

    Again, the above code is equivalent to the following.

    let x = (foo !== null && foo !== undefined) ? foo : bar();
    
    0 讨论(0)
  • 2020-11-22 00:04
    return val || 'Handle empty variable'
    

    is a really nice and clean way to handle it in a lot of places, can also be used to assign variables

    const res = val || 'default value'
    
    0 讨论(0)
  • 2020-11-22 00:05

    If you prefer plain javascript try this:

      /**
       * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
       * length of `0` and objects with no own enumerable properties are considered
       * "empty".
       *
       * @static
       * @memberOf _
       * @category Objects
       * @param {Array|Object|string} value The value to inspect.
       * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
       * @example
       *
       * _.isEmpty([1, 2, 3]);
       * // => false
       *
       * _.isEmpty([]);
       * // => true
       *
       * _.isEmpty({});
       * // => true
       *
       * _.isEmpty('');
       * // => true
       */
    
    function isEmpty(value) {
        if (!value) {
          return true;
        }
        if (isArray(value) || isString(value)) {
          return !value.length;
        }
        for (var key in value) {
          if (hasOwnProperty.call(value, key)) {
            return false;
          }
        }
        return true;
      }
    

    Otherwise, if you are already using underscore or lodash, try:

    _.isEmpty(value)
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-11-22 00:06

    You can just check if the variable has a truthy value or not. That means

    if( value ) {
    }
    

    will evaluate to true if value is not:

    • null
    • undefined
    • NaN
    • empty string ("")
    • 0
    • false

    The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

    Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

    if( typeof foo !== 'undefined' ) {
        // foo could get resolved and it's defined
    }
    

    If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

    Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

    0 讨论(0)
提交回复
热议问题