在 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值