iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
Mobile Development

刮掉Web Development的我,與撿到的Android Development系列 第 25

[Lesson25] Kotlin - Array

基本型態陣列
Kotlin 已經有內建一些陣列物件,如 ByteArray、IntArray、DoubleArray 等。它們正好是存放基本資料型態的元素,宣告時也有對應的建構式可使用。

// 僅僅只是宣告,尚未賦予元素值
val scores = IntArray(5)
// 元素值是已知的情況
// 用「Of」結尾的方法宣告,代表可以同時給予元素值
val scores = intArrayOf(68, 90, 76, 88, 92)

存取陣列元素

val names = arrayOf("Anna", "Bonnie", "Cynthia", "Darcy", "Edison")

val scores = IntArray(4)
scores[0] = 10
scores[1] = 20
scores[2] = 30
scores[3] = 40

// 將元素逐一取出,賦值給臨時變數
for (score in scores) {
    println(score)
}

// 由陣列提供索引範圍
// 陣列的 indices 方法會回傳索引的範圍,其順序為 0 到 陣列容量-1
for (i in scores.indices) {
    println(scores[i])
}

// size建立範圍
for (i in 0 until scores.size) {
    printn(scores[i])
}

//  withIndex 方法會回傳多個 IndexedValue 物件,包含索引與元素兩項資料,與 key-value 的概念類似
for ((i, value) in names.withIndex()) {
    println("${i + 1}. ${value.toUpperCase()}")
}

謝謝大家願意花時間閱讀,小弟弟我在此鞠躬/images/emoticon/emoticon41.gif


上一篇
[Lesson24] Kotlin - 條件
下一篇
[Lesson26] Kotlin - Inheritance
系列文
刮掉Web Development的我,與撿到的Android Development30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言