JavaScript 或 Angular4 中的奇怪三元条件
Strange ternary condition in JavaScript or Angular4
我正在编写代码,我在视图中找到了这段代码。据我所知,三元条件包含一个“?”然后是 2 组指令,用冒号“:”分隔。我不明白这个三元运算符是如何工作的 - 因为它有 3 个问号,只有 1 个冒号。
三元运算符语法:
var result = condition? if true do this : if false do this;
自定义代码写在Angular:
<p>{{ myModal?.subTotal!=null ? '$'+myModal?.subTotal : '' }}</p>
谁能解释一下这个三元条件是怎么写的?
看这部分 - myModal?.subTotal != null
如果 myModal
是 undefined or null
,return false
。否则访问它是 subTotal
属性 如果它不是 null
return true
,否则 false
.
这与myModal && myModal.subTotal != null
相同
更多可以看Documentation.
本例中第一个和最后一个问号不是三元运算符。
myModal?.subTotal!=null ? '$'+myModal?.subTotal : ''
(condition ) ? (if ) : (else)
详情见The safe navigation operator (?.
) and null property paths。
The Angular safe navigation operator (?.
) is a fluent and convenient way to guard against null and undefined values in property paths.
我正在编写代码,我在视图中找到了这段代码。据我所知,三元条件包含一个“?”然后是 2 组指令,用冒号“:”分隔。我不明白这个三元运算符是如何工作的 - 因为它有 3 个问号,只有 1 个冒号。
三元运算符语法:
var result = condition? if true do this : if false do this;
自定义代码写在Angular:
<p>{{ myModal?.subTotal!=null ? '$'+myModal?.subTotal : '' }}</p>
谁能解释一下这个三元条件是怎么写的?
看这部分 - myModal?.subTotal != null
如果 myModal
是 undefined or null
,return false
。否则访问它是 subTotal
属性 如果它不是 null
return true
,否则 false
.
这与myModal && myModal.subTotal != null
更多可以看Documentation.
本例中第一个和最后一个问号不是三元运算符。
myModal?.subTotal!=null ? '$'+myModal?.subTotal : ''
(condition ) ? (if ) : (else)
详情见The safe navigation operator (?.
) and null property paths。
The Angular safe navigation operator (
?.
) is a fluent and convenient way to guard against null and undefined values in property paths.