Kotlin for循环

【Kotlin for循环】Kotlin for循环用于多次迭代程序的一部分。它遍历数组, 范围, 集合或任何提供迭代的内容。 Kotlin for循环等效于C#等语言中的foreach循环。
Kotlin中for循环的语法:

for (item in collection){//body of loop}

遍历数组
让我们看一个简单的例子, 迭代数组的元素。
fun main(args : Array< String> ) {val marks = arrayOf(80, 85, 60, 90, 70)for(item in marks){println(item)}}

输出:
8085609070

如果for循环的主体仅包含一行语句, 则不必将其括在大括号{}中。
fun main(args : Array< String> ) {val marks = arrayOf(80, 85, 60, 90, 70)for(item in marks)println(item)}

数组的元素根据数组的索引(索引)进行迭代。例如:
fun main(args : Array< String> ) {val marks = arrayOf(80, 85, 60, 90, 70)for(item in marks.indices)println("marks[$item]: "+ marks[item])}

输出:
marks[0]: 80marks[1]: 85marks[2]: 60marks[3]: 90marks[4]: 70

遍历范围
让我们看一个迭代范围元素的例子。
fun main(args : Array< String> ) {print("for (i in 1..5) print(i) = ")for (i in 1..5) print(i)println()print("for (i in 5..1) print(i) = ")for (i in 5..1) print(i)// prints nothingprintln()print("for (i in 5 downTo 1) print(i) = ")for (i in 5 downTo 1) print(i)println()print("for (i in 5 downTo 2) print(i) = ")for (i in 5 downTo 2) print(i)println()print("for (i in 1..5 step 2) print(i) = ")for (i in 1..5 step 2) print(i)println()print("for (i in 5 downTo 1 step 2) print(i) = ")for (i in 5 downTo 1 step 2) print(i)}

输出:
for (i in 1..5) print(i) = 12345for (i in 5..1) print(i) = for (i in 5 downTo 1) print(i) = 54321for (i in 5 downTo 2) print(i) = 5432for (i in 1..5 step 2) print(i) = 135for (i in 5 downTo 1 step 2) print(i) = 531

    推荐阅读