简介:
Dart中的流程控制语句:
- if and else
- for loops
- while and do-while loops
- break and continue and return
- switch and case
- assert
if and else:
if (isRaining()) {
you.bringRainCoat();
}
else if (isSnowing()) {
you.wearJacket();
}
else {
car.putTopDown();
}
for loops:
- for-i
- for-in
- while
- do-while
// for-i
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());
// for-in
final intList = [1, 2, 3];
for (final item in intList) {
print(item);
}
while (!isDone()) {
doSomething();
}
do {
printLine();
} while (!atEndOfPage());
// 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();
}
// return 返回值,退出当前函数,退出函数中的所有寻循环
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (i > j) {
retrun 0;
}
}
}
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();
}
// 在开发过程中,使用一个assert语句- assert(condition, optionalMessage);-如果布尔条件为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'));
网友评论