for
The for
statement initiates loop logic, allowing the iteration of a range of values.
The standard three-component FOR loop:
for init?; condition?; post? { }
function main() {
let list = [0, 10, 20]
for (let i = 0; i < len(list); i++) {
printf("index: %d: value: %d", i, list[i])
if (i == 5) {
printf("break")
break // break out of the current for loop
} else {
continue // skip the current iteration of the for loop
}
}
return {}
}
Alternative for-each
type loops:
for <index> <entry> = range <list> { }
for <key> <value> = range <map> { }
Note: The
for ... range
loop also supportsutf8
encoded string. In this case, the index of the loop is the starting position of the currentrune
, as measured by bytes. See the example below:
function main() {
let lst = [0, 10, 20]
for i, v = range lst {
printf("index: %d: value: %d", i, v)
}
let map = {x:0, y:10, z:20}
for k, v = range map {
printf("key: %s: value: %d", k, v)
}
// works for utf8 encoded strings
let nihongo = "日本語"
for i, s = range nihongo {
printf("i:%d s:%s", i, s)
}
// i:0 s:日
// i:3 s:本
// i:6 s:語
return {}
}
Note: The
range
keyword inFOR
loops are not part of the ES6 standards.
Break
Breaks out of the current FOR
loop
function main() {
...
if (i == 5) {
printf("break")
break // break out of the current for loop
} else {
continue // skip the current iteration of the for loop
}
...
}
Continue
Skips the current iteration of the FOR
loop