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

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

当前回答

可以使用参数成为数组的参数滤器

函数validateAttributes(arg1、arg2、arg3、arg4){var args=对象.values(参数);return(args.filter(x=>x===null||!x))。长度<=0}console.log(validateAttributes('1',2,3,4));console.log(validateAttributes('1',2,3,null));console.log(validateAttributes('1',未定义,3,4));console.log(validateAttributes('1',2,'',4));console.log(validateAttributes('1',2,3,null));

其他回答

您可以只检查变量是否具有真实值。这意味着

if (value) {
    // do something..
}

如果值不是:

无效的未定义NaN公司空字符串(“”)0假的

上面的列表表示ECMA-/Javascript中所有可能的错误值。在ToBoolean部分的规范中找到它。

此外,如果您不知道变量是否存在(也就是说,如果声明了变量),则应使用typeof运算符进行检查。例如

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

如果您可以确定至少声明了一个变量,那么应该直接检查它是否具有如上所示的真实值。

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

当引用或函数可能未定义或为空时,可选的链接运算符提供了一种简化通过连接对象访问值的方法。

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

可以在可选链接之后使用零合并运算符,以便在未找到任何值时构建默认值:

let customer = {
  name: "Carl",
  details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city

仅对未定义和null返回false:

返回值??假的

如果您正在使用TypeScript,并且不想考虑“值为假”,那么这就是您的解决方案:

首先:从“util”导入{isNullOrUndefined};

然后:isNullOrUndefined(this.yourVariableName)

请注意:如下文所述,现在已弃用此选项,请改用value==undefined||value==null。裁判。