選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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

示例

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
// Outputs Volvo 
自己動手試一試 »

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

示例

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
// Outputs 4 
自己動手試一試 »


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 陣列中的所有元素

示例

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
  println(x)
}
自己動手試一試 »


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援