一般問號使用的時機為,如果有某物件則判斷某物件屬性 ... 等,像是
if obj?.value
console.log "obj exists, obj.value exists, obj.value isn't 0 and obj.value isn't ''"
這邊則討論較為特別的使用情況:
console.log "obj.value? is true" if obj.value?
console.log "obj.value is true" if obj.value
以上兩行敘述,主要的差別在 obj.value 為 0 或者 "" 時會表現不一樣,
也就是情況一和二:
### Condition 1
obj =
name: "aaa"
value: 0
# obj.value? is true
### Condition 2
obj =
name: "aaa"
value: ""
# obj.value? is true
以下是兩者表現相同的情況:
### Condition 3
obj =
name: "aaa"
# NO OUTPUT.
### Condition 4
obj =
name: "aaa"
value: null
# NO OUTPUT.
### Condition 5
obj =
name: "aaa"
value: {}
## obj.value? is true
## obj.value is true
### Condition 6
obj =
name: "aaa"
value: []
## obj.value? is true
## obj.value is true
轉成 Javascript 後比較清楚,分別為:
// if obj.value?
if(typeof value !== "undefined" && obj.value !== null) {
console.log("obj.value? is true");
}
// if obj.value
if(obj.value) {
console.log("obj.value is true");
}