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

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

当前回答

这是最安全的支票,我还没有看到它像这样贴在这里:

if (typeof value !== 'undefined' && value) {
    //deal with value'
};

它将涵盖从未定义价值的情况,以及以下任何情况:

无效的undefined(未定义的值与从未定义的参数不同)0“”(空字符串)假的NaN公司

已编辑:更改为严格相等(!==),因为这是现在的标准;)

其他回答

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

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

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

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

typeof foo != "undefined"

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

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

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

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

or

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

如果您喜欢纯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)

您可以使用零合并运算符??检查空值和未定义值。参见MDN文档

null ?? 'default string'; // returns "default string"

0 ?? 42;  // returns 0

(null || undefined) ?? "foo"; // returns "foo"
function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

它还将检查空格(“”)以及以下内容:

null,未定义,NaN,空,字符串(“”),0,false