5.Control flow statements-流程控制(Dart中文文檔)

你能夠使用以下流程控制符:數組

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert
    同時,你能夠用try-catch 和throw去跳出流程控制邏輯,並在異常代碼塊中進行處理。

If and else

下面是if和else配合使用的示例:閉包

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

有點要注意,Dart語言不像JavaScript,if判斷必須是Boolean類型對象,不能將null看做falseless

For loops

for循環示例:函數

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

在for循環中局部變量再閉包函數中使用,變量值將會是當時的快照值,後續i變更,也不會改變。這個和JavaScript不一樣。工具

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

上面的代碼,將先輸出0,再輸出1。而在JavaScript中,都是輸出2,這就是兩個之間的一個差別oop

對一個數組對象循環時,若是你不須要知道循環的計數器,能夠用forEach寫法。this

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

數組或者集合也能夠用for-in的寫法作循環。url

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

While and do-while

while是前置判斷的循環寫法:翻譯

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

do-while 是後置判斷的循環寫法:debug

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

Break and continue

你能夠用break終止循環:

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

能夠用continue 跳過循環中的一次操做:

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

若是你是對數組或者集合操做,能夠用以下寫法:

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

Switch and case

switch能夠用數值,字符串,編譯常量做爲判斷值,case後面的對象必須在類中初始化,不能在父類中,經過該對象的類不能重載==。另外,枚舉類型也能夠做爲判斷條件。

非空的case,必須使用break,coutinue,throw,return 結束,不然將編譯錯誤。

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();
}

Dart的非空case必須break,除非你採用coutinue進行跳轉。

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

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

Dart支持空的case,處理邏輯和其後續case相同。

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

若是在非空的case中,你但願switch繼續向下判斷,能夠用continue +label來實現。

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條件下,拋出異常來中斷程序執行。

// Make sure the variable has a non-null value.
assert(text != null);

// Make sure the value is less than 100.
assert(number < 100);

// Make sure this is an https URL.
assert(urlString.startsWith('https'));

注意:assert在生產模式將被忽略。Flutter能夠經過debug模式啓用assert,IDE上面,只有dartdevc默認支持dart,其它工具,好比dart,dart2js,須要用--enable-asserts來開啓assert

assert的帶2個參數寫法:

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

第六篇準備翻譯 Exceptions 異常

相關文章
相關標籤/搜索