Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Lấy chỉ số hiện tại của mảng khi dùng forEach trong Kotlin

Giới thiệu

Cần truy cập index khi duyệt mảng. Kotlin cung cấp forEachIndexed() và withIndex().

1. forEachIndexed()

Inline function nhận index và element riêng biệt.

fun main() {
    var subject = listOf("Java", "Kotlin", "JS", "C")
    subject.forEachIndexed { index, element ->
        println("index = $index, item = $element")
    }
}

Kết quả

index = 0, item = Java
index = 1, item = Kotlin
index = 2, item = JS
index = 3, item = C

2. withIndex()

Trả về Iterable của IndexedValue, dùng với for loop.

fun main() {
    var subject = listOf("Java", "Kotlin", "JS", "C")
    for ((index, value) in subject.withIndex()) {
        println("The subject of $index is $value")
    }
}

Kết quả

The subject of 0 is Java
The subject of 1 is Kotlin
The subject of 2 is JS
The subject of 3 is C

Cả hai cách đều cho phép truy cập index và value cùng lúc.