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

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

当前回答

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

其他回答

检查值是否未定义或为空的详细方法为:

return value === undefined || value === null;

您也可以使用==运算符,但这需要您了解所有规则:

return value == null; // also returns true if value is undefined

这里是我的-如果值为null、undefined等或空白(即仅包含空格),则返回true:

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}

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

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

我认为使用?操作员稍微干净一点。

var ? function_if_exists() : function_if_doesnt_exist();
return val || 'Handle empty variable'

是在许多地方处理它的一种非常好且干净的方法,也可以用于分配变量

const res = val || 'default value'