如何获得索引在一个为每个循环?我想每次迭代都打印数字

例如

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

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

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

如何得到i?


当前回答

Android中forEachIndexed的工作示例

用索引迭代

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}

使用索引更新列表

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}

其他回答

或者,你可以使用withIndex库函数:

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

控制流:if, when, for, while: https://kotlinlang.org/docs/reference/control-flow.html

使用索引

for (i in array.indices) {
    print(array[i])
}

如果你想要值和索引,使用withIndex()

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

参考:kotlin中的Control-flow

请试一次。

yourList?.forEachIndexed { index, data ->
     Log.d("TAG", "getIndex = " + index + "    " + data);
 }

Android中forEachIndexed的工作示例

用索引迭代

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}

使用索引更新列表

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}

除了@Audi提供的解决方案,还有forEachIndexed:

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