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

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

    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)
    

提交回复
热议问题