在 Kotlin 中获取 forEach 循环的当前索引
了解 forEach
循环中项目的当前索引可以帮助你找到要查找的项目的位置。本文将通过不同的方式来查找 forEach
循环的当前索引。
有三种不同的方法可以得到我们想要的,它们是:
- 使用
forEachIndexed()
- 使用
withIndex()
- 使用
indices
在 Kotlin 中使用 forEachIndexed()
在 forEach
循环中获取项目的当前索引
我们可以使用 forEachIndexed()
函数来检索当前索引。它是一个接受数组作为输入的内联函数。
forEachIndexed()
输出索引项及其值。
使用 forEachIndexed()
函数的语法如下。
collection.forEachIndexed { index, element ->
// ...
}
让我们举个例子来了解它是如何工作的。我们将创建一个数组 Student
并使用 forEachIndexed()
遍历它以获取索引和值作为以下示例中的输出。
fun main() {
var Student = listOf("Virat", "David", "Steve", "Joe", "Chris")
Student.forEachIndexed {index, element ->
println("The index is $index and the item is $element ")
}
}
输出:
在 Kotlin 中使用 withIndex()
在 forEach
循环中获取项目的当前索引
除了 forEachIndexed()
,我们还可以使用 withIndex()
函数在 Kotlin 的 forEach
循环中获取项目的当前索引。
它是一个库函数,允许通过循环访问索引和值。
我们将再次使用相同的数组,但这次使用 withIndex()
函数来访问 Student
数组的索引和值。
fun main() {
var Student = listOf("Virat", "David", "Steve", "Joe", "Chris")
for ((index, element) in Student.withIndex()) {
println("The index is $index and the item is $element ")
}
}
输出:
在 Kotlin 中使用 Indices
在 forEach
循环中获取项目的当前索引
我们还可以使用 indices
关键字来获取当前索引。使用 indices
的语法如下。
for (i in array.indices) {
print(array[i])
}
让我们在我们的 Student
数组中使用这个语法来访问索引和值。
fun main(args : Array<String>){
val Student = arrayOf("Virat", "David", "Steve", "Joe", "Chris")
for (i in Student.indices){
println("Student[$i]: ${Student[i]}")
}
}
输出:
在 Kotlin 中使用 filterIndexed()
获取数组项的索引
我们可以使用上述函数获取当前索引。但是,如果我们只想访问特定的索引而不是所有索引怎么办。
我们可以使用 filterIndexed()
函数来做到这一点。
filterIndexed()
函数接受一个条件作为参数。根据我们传递的条件,该函数可以过滤输出以显示所需的索引。
让我们使用 filterIndexed()
函数仅访问 Student
数组中偶数索引处的值。
fun main(args : Array<String>){
val Student = arrayOf("Virat", "David", "Steve", "Joe", "Chris")
.filterIndexed { index, _ -> index % 2 == 0 }
.forEach { println(it) }
}
输出:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。