For loop
Simple loop
Syntax
for <init>, <end> <body>
init
is an initializer, explained belowend
is an expression, the value which initial variable iterates through tobody
is a statement
The initializer
It could be:
A variable declaration
Use
A assign expression
If the target vairable in the assignment is not defined, it will be defined by the let keyword implicitly.
Examples
Counting numbers
Printing even numbers
Counting down
C-style loop
But no parenthese, comma instead of semicolon.
Syntax
for <init>, <cond>, <updater> <body>
init
is loop initializer, it could be an expressioncond
is loop condition, an expressionupdater
is an expression, which is executed after the loop body
Examples
Basic
Without updater
If the last comma is removed, the loop becomes Simple loop.
For-each loop
Iterating through an array, map.
Syntax
for <first> [, <second>] : <expr> <body>
first
- the first variablesecond
- the second variable (optional)expr
- an expression to be evaluated, value must be a map or an array
Examples
With an array:
Just use for v : arr
to get the value only.
With a map:
Depend on the implementation, the key - value pairs may not in input order.
So the output of above example could be:
... or
Like array, just get the key only:
Infinite loop
Pure
With initializer
Last updated