Kotlin Arrays
Kotlin 陣列
Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value.
To create an array, use the arrayOf()
function, and place the values in a comma-separated list inside it
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
訪問陣列元素
You can access an array element by referring to the index number, inside square brackets.
In this example, we access the value of the first element in cars
Note: Just like with Strings, Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
更改陣列元素
要更改特定元素的值,請參考索引號:
示例
cars[0] = "Opel"
示例
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// Now outputs Opel instead of Volvo
自己動手試一試 »
Array Length / Size
To find out how many elements an array have, use the size
property
Check if an Element Exists
You can use the in
operator to check if an element exists in an array
示例
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}
自己動手試一試 »
迴圈遍歷陣列
Often when you work with arrays, you need to loop through all of the elements.
You can loop through the array elements with the for
loop, which you will learn even more about in the next chapter.
下面的示例輸出了 cars 陣列中的所有元素