Dart的for总结

/ 默认分类 / 2 条评论 / 2584浏览

import 'dart:io';

void main(List<String> args) {
  var message = ['map', 'list', 'set'];
  for (var i = 0; i < 2; i++) {
    print(message[i]);
  }

  // 捕获异常
  var callbacks = [];
  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print(i));
  }
  print(callbacks);
  for (final c in callbacks) {
    print('------');
    c();
  }

  // for-in 一个 list 或者set
  var obj = [12, 13, 14];

  for (var prop in obj) {
    print(prop);
  }

  // while循环
  var num = 5;

  while (num >= 2) {
    num--;
    print("num : ${num}");
  }
  // while 循环会在执行循环体前先判断条件:
  // while (!isDone()) {
  //   doSomething();
  // }

  //do-while 循环则会 先执行一遍循环体 再判断条件:
  do {
    doSomething();
  } while (!isDone());

  // forEach
  var collection = [1, 2, 3];
  collection.forEach((v) => print('forEach.value : ${v}')); // 1 2 3
  // forEach map
  var userMap = {"name": "Maxsu", 'Email': 'maxsu@yiibai.com'};
  userMap.forEach((k, v) => print('${k}: ${v}'));
}

isDone() {
  return true;
}

doSomething() {
  sleep(Duration(seconds: 1));
  print('while don\'t stop');
}

  1. 这篇文章写得深入浅出,让我这个小白也看懂了!

    回复
  2. 看 dart呢

    回复