reactjs 检查变量是否为空快捷方式||未定义的||空字符串||假的

6za6bjd0  于 2023-04-20  发布在  React
关注(0)|答案(3)|浏览(205)

我正在寻找检查,如果我的变量是以下之一:

null || undefined || empty string || false

现在它看起来凌乱而漫长:

const userHasPhoneNumber = user.phone === undefined || 
                           user.phone === "" || 
                           user.phone === false ||
                           user.phone === null ? false : true;

有近路吗?

55ooxyrt

55ooxyrt1#

使用JavaScript的!!,对于null""undefinedfalse,将变为false

const user = {
  phone_1: null,
  phone_2: "",
  phone_3: undefined,
  phone_4: false
};

console.log(!!user.phone_1);  // false
console.log(!!user.phone_2);  // false
console.log(!!user.phone_3);  // false
console.log(!!user.phone_4);  // false

注意请谨慎使用,因为某些结果可能与预期不同,this answer显示完整列表。

liwlm1x9

liwlm1x92#

你可以快捷方式x === undefined || x === nullx == null。对于其他的,没有快捷方式,因为也有一些错误的数字值。但是你可以这样做

const userHasPhoneNumber = typeof user.phone == "number" || !!user.phone
dgsult0t

dgsult0t3#

如果你把这个字符串强制转换成布尔值,那么它应该检查你所有的条件,这基本上就是检查user.phone是否为真。
这取决于你想如何使用它。如果你想在条件中使用它,例如if(userHasPhoneNumber) ...,那么你可以直接使用字符串:if(user.phone),因为它将强制转换为布尔值。
如果你真的需要一个布尔变量,那么需要显式地将其转换为布尔值:
通过const userHasPhoneNumber = Boolean(user.phone);const userHasPhoneNumber = !!user.phone;
请注意,正如@Bergi评论的那样,有更多的值被强制转换为false值(假值),例如NaN或数字0(字符串“0”将强制为true),因此这取决于输入的内容。如果它不是数字,而是字符串/boolean/null/undefined,应该没问题。下面是所有falsy值的列表以供参考:https://developer.mozilla.org/en-US/docs/Glossary/Falsy

相关问题