如何在 Kotlin 中使用 forEach 循环获取数组的当前索引?
androidmobile developmentapps/applicationskotlin 更新于 2026/2/10 6:37:17
有时需要访问数组的索引。在本文中,我们将了解如何在 Kotlin 中使用 forEach 循环访问数组的索引。
示例:使用 forEachIndexed()
除了使用 forEach() 循环之外,您还可以在 Kotlin 中使用 forEachIndexed() 循环。forEachIndexed 是一个内联函数,它以数组作为输入,并且可以分别访问其 索引 和 值。
在下面的示例中,我们将遍历 "Subject" 数组,并将索引与 值 一起打印。
示例
fun main() {
var subject = listOf("Java", "Kotlin", "JS", "C")
subject.forEachIndexed {index, element ->
println("index = $index, item = $element ")
}
}
输出
它将生成以下输出 −
index = 0, item = Java index = 1, item = Kotlin index = 2, item = JS index = 3, item = C
示例:使用 withIndex()
withIndex() 是 Kotlin 的一个库函数,使用它您可以访问数组的索引和相应的值。在下面的示例中,我们将使用同一个数组,并使用 withIndex() 打印其值和索引。这必须与 for 循环一起使用。
示例
fun main() {
var subject=listOf("Java", "Kotlin", "JS", "C")
for ((index, value) in subject.withIndex()) {
println("The subject of $index is $value")
}
}
输出
它将生成以下输出 −
The subject of 0 is Java The subject of 1 is Kotlin The subject of 2 is JS The subject of 3 is C

