Dart Basics — loop

Graph LR A(loop) --> B(for loop) A --> C(for... In loop) A --> D(while loop) A --> E(do... While loop) A --> F(loop control) F --> G(break statement) F --> H(continue) A --> J(switch... case) A --> K(assert)

The for loop

The number of times a for loop executes a code block, which can be used to iterate over a fixed set of values.

  / / a for loop
  for (var i = 0; i < 10; i++) {
    print(i);  / / 0,1,2,3,4,5,6,7,8,9
  }
Copy the code

for … In circulation

for … The in loop is used to loop through the properties of an object.

  // for ... In circulation
  var list = ['apple'.'chestnut'.Little Apple];
  for (var item in list) {
    print(item); // Item indicates the contents of each item
  }
Copy the code

The while loop

Each time the specified condition evaluates to true, the while loop executes the instruction, otherwise it does not execute.

  / / while loop
  var i = 0;
  while(i < 10) {print(i);
    i++;
  }
Copy the code

The do… The while loop

do … A while loop is similar to a while loop, except that it does… The while loop executes a while loop whether or not the while is true.

  // Do while loop
  var i = 10;
  do {
    print(i);
    i++;
  } while(i > 15);
Copy the code

Cycle control

Break statement

The break statement is used to control the structure. Using a break in a loop causes the program to exit the loop.

 for (var i = 0; i < 5; i++) {
    print("i= ${i}");
    for (var j = 0; j < 5; j++) {
        print("j = ${j}");
       if (j > 3 ) break; }}Copy the code

continue

The continue statement skips subsequent statements of the current iteration.

 var num = 0;
 var count = 0;

 for(num = 0;num< =20;num{+ +)if (num % 2= =0) {
       continue;
    }
    count++;
 } 
Copy the code

switch … case

The switch statement evaluates the expression, matches the value of the expression to the case clause, and executes the statement associated with that case.

  var grade = "A";
  switch (grade) {
    case "A":
      {
        print("Very good");
      }
      break;
    case "B":
      {
        print("More than enough.");
      }
      break;
    case "C":
      {
        print("Pass");
      }
      break;
    case "D":
      {
        print("Fail");
      }
      break;
    default:
      {
        print("Your test paper was stolen.");
      }
      break;
  }

Copy the code

assert

The program continues if the Boolean condition in the assert statement is true; otherwise, the program interrupts

// Verify that the variable value is not empty.
assert(text ! =null);

// Verify that the variable value is greater than 50.
assert(number > 50);

Copy the code

Tip: Assert statements are valid only in the development environment, not in production.