【发布时间】:2023-03-05 02:54:01
【问题描述】:
如何在 for each 循环中获取索引?我想为每第二次迭代打印一次数字
例如
for (value in collection) {
if (iteration_no % 2) {
//do something
}
}
在java中,我们有传统的for循环
for (int i = 0; i < collection.length; i++)
如何获取i?
【问题讨论】:
如何在 for each 循环中获取索引?我想为每第二次迭代打印一次数字
例如
for (value in collection) {
if (iteration_no % 2) {
//do something
}
}
在java中,我们有传统的for循环
for (int i = 0; i < collection.length; i++)
如何获取i?
【问题讨论】:
除了@Audi提供的解决方案,还有forEachIndexed:
collection.forEachIndexed { index, element ->
// ...
}
【讨论】:
break?
return@forEachIndexed,它本质上将作为continue跳到下一个元素。如果需要中断,则必须将其包装在一个函数中,并在循环中使用return 从该封闭函数返回。
continue如果你需要这样的功能使用@Audi回答
使用indices
for (i in array.indices) {
print(array[i])
}
如果您想要价值和索引,请使用withIndex()
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
【讨论】:
或者,您可以使用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循环
for ((i, item) in arrayList.withIndex()) { }
【讨论】:
arrayList.subList(0, arrayList.size/2)。
forEachIndexed 在 Android 中的工作示例使用索引迭代
itemList.forEachIndexed{index, item ->
println("index = $index, item = $item ")
}
使用索引更新列表
itemList.forEachIndexed{ index, item -> item.isSelected= position==index}
【讨论】:
看来你真正要找的是filterIndexed
例如:
listOf("a", "b", "c", "d")
.filterIndexed { index, _ -> index % 2 != 0 }
.forEach { println(it) }
结果:
b
d
【讨论】:
.forEach(::println)
Ranges 在这种情况下也会导致代码可读:
(0 until collection.size step 2)
.map(collection::get)
.forEach(::println)
【讨论】:
(0..collection.lastIndex step 2)