流程控制语句
可以使用下面的语句来控制Dart
代码的流程:
-
if
andelse
-
for
loops -
while
anddo-while
loops -
break
andcontinue
-
switch
andcase
assert
使用try-catch
和throw
还能影响控制流程的 跳转,详情请参考Exceptions.
If and else
Dart
支持if
语句以及可选的`else1,例如下面的示例。 另参考conditional expressions
if (isRaining()) {
you.bringRainCoat();
} else if (isSnowing()) {
you.wearJacket();
} else {
car.putTopDown();
}
注意,Dart
中和JavaScript
对待 true
的区别。 参考 Booleans
For loops
可以使用标准的for
循环:
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
Dart
的for
循环中的闭包能获取循环变量的值,避免了像Javascript
中的常见陷阱,如下例
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
正如我们所期待的,输出结果分别是0和1,但相反的情况可以在Javascript
中见到,输出分别为2和2。
如果要遍历的对象实现了Iterable
接口,则可以使用 forEach()
方法。如果没必要当前遍历的索引,则使用 forEach()
方法 是个非常好的选择:
candidates.forEach((candidate) => candidate.interview());
List 和 Set 等实现了 Iterable 接口的类还支持 for-in 形式的 iteration
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
循环是先执行循环代码再判断条件:
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();
}
上面的代码在实现 Iterable 接口对象上可以使用下面的写法:
candidates
.where((c) => c.yearsExperience >= 5)
.forEach((c) => c.interview());
Switch and case
Dart
中的 Switch
语句使用 ==
比较 integer
、string
、或者编译时常量。 比较的对象必须都是同一个类的实例(并且不是 其之类),class
必须没有覆写 ==
操作符。Enumerated types非常适合 在 switch
语句中使用。
注意:
Dart
中的Switch
语句仅适用于有限的情况, 例如在解释器或者扫描器中使用。
每个非空的case
语句都必须有一个break
语句。 另外还可以通过 continue
、 throw
或者return
来结束非空case
语句。
当没有case
语句匹配的时候,可以使用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
语句, 编译的时候将会出现一个错误:
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
然而,Dart
支持空的case
分句,并允许使用从一个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
语句中继续执行,则可以 使用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
如果一个布尔条件值为false
,使用assert
语句来中断正常执行的代码。你可以在本教程中找到一些assert
语句的样例。这里有一些例子:
// 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语句仅仅只能在调试模式下使用,在生产模式下没有任何作用。
为了给assert
添加相关信息,可以添加字符串作为第二个参数
assert(urlString.startsWith('https'),
'URL ($urlString) should start with "https".');
在assert
语句后面的括号中,第一个参数可以加入任何表示布尔值或者函数的表达式。如果表达式的值或者函数返回值true
,则assert语句成功并继续执行代码。如果值为false
,则assert
语句失败并抛出一个异常 (an AssertionError)。
网友评论