如何在 Kotlin 中使用 forEach 迴圈時獲取陣列的當前索引?


有時需要訪問陣列的索引。在本文中,我們將瞭解如何在 Kotlin 中使用 forEach 迴圈訪問陣列的索引。

示例:使用 forEachIndexed()

您可以使用 Kotlin 中的 forEachIndexed() 迴圈,而不是使用 forEach() 迴圈。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

更新於: 2021年10月27日

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.