運算符(下)

2020-02-03 23:51 更新

條件表達式

Dart有兩個運算符,有時可以替換 if-else 表達式, 讓表達式更簡潔:

condition ? expr1 : expr2
如果條件為 true, 執(zhí)行 expr1 (并返回它的值): 否則, 執(zhí)行并返回 expr2 的值。
expr1 ?? expr2
如果 expr1 是 non-null, 返回 expr1 的值; 否則, 執(zhí)行并返回 expr2 的值。

如果賦值是根據(jù)布爾值, 考慮使用 ?:。

var visibility = isPublic ? 'public' : 'private';

如果賦值是基于判定是否為 null, 考慮使用 ??。

String playerName(String name) => name ?? 'Guest';

下面給出了其他兩種實現(xiàn)方式, 但并不簡潔:

// Slightly longer version uses ?: operator.
String playerName(String name) => name != null ? name : 'Guest';

// Very long version uses if-else statement.
String playerName(String name) {
  if (name != null) {
    return name;
  } else {
    return 'Guest';
  }
}


級聯(lián)運算符 (..)

級聯(lián)運算符 (..) 可以實現(xiàn)對同一個對像進行一系列的操作。 除了調(diào)用函數(shù), 還可以訪問同一對象上的字段屬性。 這通??梢怨?jié)省創(chuàng)建臨時變量的步驟, 同時編寫出更流暢的代碼。

考慮一下代碼:

querySelector('#confirm') // 獲取對象。
  ..text = 'Confirm' // 調(diào)用成員變量。
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));

第一句調(diào)用函數(shù) querySelector() , 返回獲取到的對象。 獲取的對象依次執(zhí)行級聯(lián)運算符后面的代碼, 代碼執(zhí)行后的返回值會被忽略。

上面的代碼等價于:

var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));

級聯(lián)運算符可以嵌套,例如:

final addressBook = (AddressBookBuilder()
      ..name = 'jenny'
      ..email = 'jenny@example.com'
      ..phone = (PhoneNumberBuilder()
            ..number = '415-555-0100'
            ..label = 'home')
          .build())
    .build();

在返回對象的函數(shù)中謹慎使用級聯(lián)操作符。 例如,下面的代碼是錯誤的:

var sb = StringBuffer();
sb.write('foo')
  ..write('bar'); // Error: 'void' 沒喲定義 'write' 函數(shù)。

sb.write() 函數(shù)調(diào)用返回 void, 不能在 void 對象上創(chuàng)建級聯(lián)操作。

提示: 嚴格的來講, “兩個點” 的級聯(lián)語法不是一個運算符。 它只是一個 Dart 的特殊語法。


其他運算符

大多數(shù)剩余的運算符,已在示例中使用過:

OperatorNameMeaning
()Function applicationRepresents a function call
[]List accessRefers to the value at the specified index in the list
.Member accessRefers to a property of an expression; example: foo.bar selects property barfrom expression foo
?.Conditional member accessLike ., but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)

更多關(guān)于 ., ?. 和 .. 運算符介紹,參考 Classes.

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號