如何获取每个Kotlin的当前索引 [英] How to get the current index in for each Kotlin

查看:1089
本文介绍了如何获取每个Kotlin的当前索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取每个循环的索引... 我想为第二次迭代打印数字

How do I get the index for a for each loop... I want to print numbers for every second iteration

例如

for(value in collection) {
     if(iteration_no % 2) {
         //do something
     }
}

在Java中,我们具有传统的for循环

In java we have the traditional for loop

for(int i=0; i< collection.length; i++)

如何获取i?

推荐答案

除了@Audi提供的解决方案之外,还有

In addition to the solutions provided by @Audi, there's also forEachIndexed:

collection.forEachIndexed { index, element ->
    // ...
}

这篇关于如何获取每个Kotlin的当前索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆