在 Kotlin 中使用 forEach 循环时如何获取数组的当前索引?

有时需要访问数组的索引。在本文中,我们将看到如何在 Kotlin 中使用 forEach 循环访问数组的索引。

示例:使用forEachIndexed()

forEach()您可以forEachIndexed()在 Kotlin中使用循环,而不是使用循环。forEachIndexed 是一个内联函数,它将一个数组作为输入,并且它的索引和值可以单独访问。

在下面的示例中,我们将遍历“主题”数组,并将索引与值一起打印。

示例

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

猜你喜欢

转载自blog.csdn.net/liujun3512159/article/details/128451409