我通常會遇到這樣的條件反射,我想知道是否有一個簡短的方法來寫下面類似的東西,而不呼叫一個函式
。const currentValue = this. props.book.location.areaValueInDollars?this.props.book。 location.areaValueInDollars : 0;
uj5u.com熱心網友回復:
使用nullish凝聚運算子:
this.props。 book.location.areaValueInDollars || 0.
這里有更多關于這個主題的內容。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
uj5u.com熱心網友回復:
你可以使用短路和邏輯OR運算子.
。 。const currentValue = window['a'] || 0。
console.log(currentValue);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如果變數存在,那么第一個運算元將回傳true,使其 "短路 "并被回傳。第二個運算元只有在第一個運算元為false時才會被評估,因為運算式是從左到右評估的。
使用邏輯OR運算子有一個注意事項。如果變數是
0、null、undefined...(完整串列見Falsy values),它將回傳 false。
為了解決這個問題,我們可以使用Nullish coalescing operator,只有當左邊的運算元為null或undefined時,它才會回傳右邊的運算元。像這樣:
const currentValue = window['a'/span>] ? 0;
console.log(currentValue);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331525.html
標籤:
上一篇:不確定如何解決TypeError。_utils_ipfs__WEBPACK_IMPORTED_MODULE_5__.default.files.add不是一個函式。
下一篇:如何從一個陣串列中計算長度
