Shorthand 在 Javascript 中编写条件的方法

Shorthand way to write Conditional in Javascript

我通常 运行 编写这样的条件语句,我想知道是否有一种简便的方法可以在不调用函数的情况下编写类似下面的内容

const currentValue = this.props.book.location.areaValueInDollars ? this.props.book.location.areaValueInDollars : 0; 

使用无效合并运算符:

this.props.book.location.areaValueInDollars || 0

有关此主题的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

您可以使用短路和 Logical OR operator

const currentValue = window['a'] || 0; 

console.log(currentValue);

如果变量存在,那么第一个操作数将return true,导致它“短路”并被returned。仅当第一个操作数为 false 时才计算第二个操作数,因为表达式是从左到右计算的。


不过,使用逻辑或运算符有一个警告。如果变量是 0nullundefined...(有关完整列表,请参阅 Falsy values),它将 return false。

为了解决这个问题,我们可以使用 Nullish coalescing operator,如果左侧操作数是 nullundefined,它只会 return 右侧操作数。像这样:

const currentValue = window['a'] ?? 0; 

console.log(currentValue);