Bicep 邏輯運算子

邏輯運算子可評估布林值、傳回非 Null 值,或評估條件運算式。 若要執行這些範例,請使用 Azure CLI 或 Azure PowerShell 來部署 Bicep 檔案

運算子 名稱
&& And
|| Or
! Not
?? Coalesce
? : 條件運算式

And &&

operand1 && operand2

判斷這兩個值是否為 true。

運算元

運算元 類型 描述
operand1 boolean 檢查是否為 true 的第一個值。
operand2 boolean 檢查是否為 true 的第二個值。
更多運算元 boolean 可納入更多運算元。

傳回值

兩個值都為 True 時,為 True,否則傳回 false

範例

評估一組參數值和一組運算式。

param operand1 bool = true
param operand2 bool = true

output andResultParm bool = operand1 && operand2
output andResultExp bool = 10 >= 10 && 5 > 2

範例的輸出:

名稱 類型
andResultParm boolean true
andResultExp boolean true

若要避免 Bicep 物件 (機器翻譯) 出現「語言運算式屬性 'foo' 不存在」例外狀況,您可以使用 And 邏輯運算子,如下方範例所示:

param objectToTest object = {
  one: 1
  two: 2
  three: 3
}

output bar bool = contains(objectToTest, 'four') && objectToTest.four == 4

Or ||

operand1 || operand2

判斷其中一個值是否為 true。

運算元

運算元 類型 描述
operand1 boolean 檢查是否為 true 的第一個值。
operand2 boolean 檢查是否為 true 的第二個值。
更多運算元 boolean 可納入更多運算元。

傳回值

任一值為 true 時,為 True,否則傳回 false

範例

評估一組參數值和一組運算式。

param operand1 bool = true
param operand2 bool = false

output orResultParm bool = operand1 || operand2
output orResultExp bool = 10 >= 10 || 5 < 2

範例的輸出:

名稱 類型
orResultParm boolean true
orResultExp boolean true

若要避免出現發生「語言運算式屬性陣列索引 'x' 超出範圍」例外狀況,您可以使用 Or 邏輯運算子,如下方範例所示:

param emptyArray array = []
param numberArray array = [1, 2, 3]

output foo bool = empty(emptyArray) || emptyArray[0] == 'bar'
output bar bool = length(numberArray) >= 3 || numberArray[3] == 4

Not !

!boolValue

否定布林值。

運算元

運算元 類型 描述
boolValue boolean 已變為否定的布林值。

傳回值

否定初始值,然後傳回布林值。 如果初始值為 true,則會傳回 false

範例

not 運算子會否定該值。 這些值可以用括弧括住。

param initTrue bool = true
param initFalse bool = false

output startedTrue bool = !(initTrue)
output startedFalse bool = !initFalse

範例的輸出:

名稱 類型
startedTrue boolean false
startedFalse boolean true

Coalesce ??

operand1 ?? operand2

從運算元傳回第一個非 Null 的值。

運算元

運算元 類型 描述
operand1 字串、整數、布林值、物件、陣列 要測試是否為 null 的值。
operand2 字串、整數、布林值、物件、陣列 要測試是否為 null 的值。
更多運算元 字串、整數、布林值、物件、陣列 要測試是否為 null 的值。

傳回值

傳回第一個非 Null 值。 空字串、空白陣列和空白物件皆非 null,而會傳回<空>值。

範例

Output 陳述式會傳回非 Null 值。 輸出類型必須符合比較中的類型,否則會產生錯誤。

param myObject object = {
  isnull1: null
  isnull2: null
  string: 'demoString'
  emptystr: ''
  integer: 10
  }

output nonNullStr string = myObject.isnull1 ?? myObject.string ?? myObject.isnull2
output nonNullInt int = myObject.isnull1 ?? myObject.integer ?? myObject.isnull2
output nonNullEmpty string = myObject.isnull1 ?? myObject.emptystr ?? myObject.string ?? myObject.isnull2

範例的輸出:

名稱 類型
nonNullStr string demoString
nonNullInt int 10
nonNullEmpty string <empty>

條件運算式 ? :

condition ? true-value : false-value

評估條件並傳回值,指出條件為 true 或 false。

運算元

運算元 類型 描述
condition boolean 評估為 true 或 false 的條件。
true-value 字串、整數、布林值、物件、陣列 條件為 true 時的值。
false-value 字串、整數、布林值、物件、陣列 條件為 false 時的值。

範例

此範例會評估參數的初始值,並傳回條件為 true 或 false 的值。

param initValue bool = true

output outValue string = initValue ? 'true value' : 'false value'

範例的輸出:

名稱 類型
outValue string true 值

下一步