是否有一个通用的JavaScript函数来检查变量是否有值,并确保它不是未定义的或空的?我有这个代码,但我不确定它是否涵盖所有情况:

function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

当前回答

如果您喜欢纯javascript,请尝试以下操作:

  /**
   * 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;
  }

否则,如果您已经使用下划线或lodash,请尝试:

_.isEmpty(value)

其他回答

try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

我认为使用try-catch可以避免任何空检查错误,在Angular或JavaScript中也是如此只是捕获空异常并在其中处理。

第一个评分最好的答案是错误的。若值未定义,则会在现代浏览器中引发异常。您必须使用:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)

如果变量尚未声明,则无法使用函数测试未定义,因为会出现错误。

if (foo) {}
function (bar) {}(foo)

如果尚未声明foo,则两者都将生成错误。

如果要测试变量是否已声明,可以使用

typeof foo != "undefined"

如果您想测试foo是否已声明,并且它有一个值,您可以使用

if (typeof foo != "undefined" && foo) {
    //code here
}

你做得有点过头了。要检查变量是否没有给定值,只需要检查undefined和null。

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

这是假设0、“”和对象(甚至是空对象和数组)是有效的“值”。

您可以始终使用loadash函数,例如_.isNil或_.isUndefined。它们非常容易使用。