📅  最后修改于: 2021-01-05 07:17:54             🧑  作者: Mango
Kotlin for循环用于多次迭代程序的一部分。它遍历数组,范围,集合或任何提供迭代的内容。 Kotlin for循环等效于C#等语言中的foreach循环。
Kotlin中for循环的语法:
for (item in collection){
//body of loop
}
让我们看一个简单的例子,迭代数组的元素。
fun main(args : Array) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}
输出:
80
85
60
90
70
如果for循环的主体仅包含一行语句,则不必将其括在大括号{}中。
fun main(args : Array) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks)
println(item)
}
数组的元素根据数组的索引(索引)进行迭代。例如:
fun main(args : Array) {
val marks = arrayOf(80,85,60,90,70)
for(item in marks.indices)
println("marks[$item]: "+ marks[item])
}
输出:
marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
让我们看一个迭代范围元素的例子。
fun main(args : Array) {
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 nothing
println()
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) = 12345
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531