內容總結
- 區間表達式提供更便利、更豐富的方式去循環遍歷區間
- 解構的語法最常用於遍歷map,同時讀取key與value的值
知識要點
Map的常規遍歷
// iterating over a map
val map = mapOf(1 to “one”, 2 to “two”)
for( (key, value) in map){…}
遍歷時獲取索引
歷遍數據或列表的indices或庫函數withIndex
//1 indices
for (i in array.indices) {
println(array[i])
}
// 2 withIndex
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
區間表達式
區間表達式 = 區間創建 表達式 + 空隔 + [遍歷方向] + [步進單位]
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}