31DaysOfKotlin - Day 5: 循環,區間表達式和解構

內容總結

  • 區間表達式提供更便利、更豐富的方式去循環遍歷區間
  • 解構的語法最常用於遍歷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)
}

參考文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章