控制流程語句

2020-02-03 23:24 更新

你可以通過下面任意一種方式來控制 Dart 程序流程:

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert

使用 try-catch 和 throw 也可以改變程序流程, 詳見 Exceptions。


if 和 else

Dart 支持 if - else 語句,其中 else 是可選的, 比如下面的例子, 另參考 conditional expressions.

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}

和 JavaScript 不同, Dart 的判斷條件必須是布爾值,不能是其他類型。 更多信息,參考 Booleans 。


for 循環(huán)

進(jìn)行迭代操作,可以使用標(biāo)準(zhǔn) for 語句。 例如:

var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
  message.write('!');
}

閉包在 Dart 的 for 循環(huán)中會捕獲循環(huán)的 index 索引值, 來避免 JavaScript 中常見的陷阱。 請思考示例代碼:

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());

和期望一樣,輸出的是 0 和 1。 但是示例中的代碼在 JavaScript 中會連續(xù)輸出兩個 2 。

I如果要迭代一個實現(xiàn)了 Iterable 接口的對象, 可以使用 forEach() 方法, 如果不需要使用當(dāng)前計數(shù)值, 使用 forEach() 是非常棒的選擇;

candidates.forEach((candidate) => candidate.interview());

實現(xiàn)了 Iterable 的類(比如, List 和 Set)同樣也支持使用 for-in 進(jìn)行迭代操作 iteration :

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}


while 和 do-while

while 循環(huán)在執(zhí)行前判斷執(zhí)行條件:

while (!isDone()) {
  doSomething();
}

do-while 循環(huán)在執(zhí)行后判斷執(zhí)行條件:

do {
  printLine();
} while (!atEndOfPage());


break 和 continue

使用 break 停止程序循環(huán):

while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}

使用 continue 跳轉(zhuǎn)到下一次迭代:

for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}

如果對象實現(xiàn)了 Iterable 接口 (例如,list 或者 set)。 那么上面示例完全可以用另一種方式來實現(xiàn):

candidates
    .where((c) => c.yearsExperience >= 5)
    .forEach((c) => c.interview());


switch 和 case

在 Dart 中 switch 語句使用 == 比較整數(shù),字符串,或者編譯時常量。 比較的對象必須都是同一個類的實例(并且不可以是子類), 類必須沒有對 == 重寫。 枚舉類型 可以用于 switch 語句。

提示: 在 Dart 中 Switch 語句僅適用于有限的情況下, 例如在 interpreter 或 scanner 中。

在 case 語句中,每個非空的 case 語句結(jié)尾需要跟一個 break 語句。 除 break 以外,還有可以使用 continue, throw,者 return。

當(dāng)沒有 case 語句匹配時,執(zhí)行 default 代碼:

var command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'PENDING':
    executePending();
    break;
  case 'APPROVED':
    executeApproved();
    break;
  case 'DENIED':
    executeDenied();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}

下面的 case 程序示例中缺省了 break 語句,導(dǎo)致錯誤:

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: 丟失 break

  case 'CLOSED':
    executeClosed();
    break;
}

但是, Dart 支持空 case 語句, 允許程序以 fall-through 的形式執(zhí)行。

var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

在非空 case 中實現(xiàn) fall-through 形式, 可以使用 continue 語句結(jié)合 lable 的方式實現(xiàn):

var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    executeClosed();
    continue nowClosed;
  // Continues executing at the nowClosed label.

  nowClosed:
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

case 語句可以擁有局部變量, 這些局部變量只能在這個語句的作用域中可見。


assert

如果 assert 語句中的布爾條件為 false , 那么正常的程序執(zhí)行流程會被中斷。 在本章中包含部分 assert 的使用, 下面是一些示例:

// 確認(rèn)變量值不為空。
assert(text != null);

// 確認(rèn)變量值小于100。
assert(number < 100);

// 確認(rèn) URL 是否是 https 類型。
assert(urlString.startsWith('https'));

提示: assert 語句只在開發(fā)環(huán)境中有效, 在生產(chǎn)環(huán)境是無效的; Flutter 中的 assert 只在 debug 模式 中有效。 開發(fā)用的工具,例如 dartdevc 默認(rèn)是開啟 assert 功能。 其他的一些工具, 例如 dart 和 dart2js,支持通過命令行開啟 assert : --enable-asserts。

assert 的第二個參數(shù)可以為其添加一個字符串消息。

assert(urlString.startsWith('https'),
    'URL ($urlString) should start with "https".');

assert 的第一個參數(shù)可以是解析為布爾值的任何表達(dá)式。 如果表達(dá)式結(jié)果為 true , 則斷言成功,并繼續(xù)執(zhí)行。 如果表達(dá)式結(jié)果為 false , 則斷言失敗,并拋出異常 (AssertionError) 。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號