11.條件運算符的應用

條件運算符與流程控制語句中的條件語句作用很像。這是一種更簡潔的實現條件邏輯的方式。

var a = 3;
var b = 5;
var res = a>b ? "a>b" : "a<=b";
print(res);//a<=b

條件運算符?是一個三元的運算符。

在實際開發中,很多時候我們需要判斷某個變量的值是否為null,不為null的時候再來做某些操作。使用條件運算符的代碼如下:

var c = null;
c ??= 0;//c = c??0;
print(c);
print(c==null?"無作為":"額外操作a:$c");
print(c??"無作為");

空條件運算符也可以和賦值運算符結合組成複合運算符,示例如下:
var c = null;
c ??= 0;//與c = c??0;意義完全一樣


Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments