javascript – 空條件運算子
.這些使用?或?[]語法.
在嘗試訪問屬性之前,這些操作本質上允許您檢查您擁有的物件是否為空.如果物件為空,那麼您將獲得屬性訪問的結果為null.
int? length = customers?.Length;
所以這裡int可以為null,如果客戶為null,那麼將取值.更好的是你可以連結這些:
int? length = customers?.orders?.Length;
我不相信我們可以在JavaScript中做到這一點,但我想知道做什麼類似的最簡單的方法是什麼.一般來說,我發現連結如果塊難以閱讀:
var length = null; if(customers && customers.orders) { length = customers.orders.length; }
Js邏輯運算子返回的不是true或false,而是真正的或偽造的值本身.例如在表示式x&& y,如果x是假的,那麼它將被返回,否則y將被返回.所以運算子的真值表是正確的.
在您的情況下,您可以使用表示式客戶&& customers.orders&& customers.orders.Length獲取長度值或第一個偽造的一個.
你也可以像((客戶|| {}),訂單|| {})
(就個人而言,我不喜歡語法和可能的垃圾收集壓力)
甚至可能使用monad.
function Option(value) { this.value = value; this.hasValue = !!value; } Option.prototype.map = function(s) { return this.hasValue ? new Option(this.value[s]) : this; } Option.prototype.valueOrNull = function() { return this.hasValue ? this.value : null; } var length = new Option(customers) .map("orders") .map("length") .valueOrNull();
它比以前的所有方法都長,但是清楚地顯示出你的意圖,沒有任何魔法背後.
http://stackoverflow.com/questions/31610869/null-conditional-operators