Menu
×
   ❮   
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 数组


Kotlin 数组

数组用于在一个变量中存储多个值,而不是为每个值创建单独的变量。

要创建数组,请使用 arrayOf() 函数,并将值以逗号分隔的形式放在其中

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

访问数组元素

可以通过引用索引号(位于方括号内)来访问数组元素。

在这个例子中,我们访问了 cars 中第一个元素的值

示例

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

注意:与字符串一样,数组索引从 0 开始:[0] 是第一个元素。[1] 是第二个元素,依此类推。


更改数组元素

要更改特定元素的值,请引用其索引号

示例

cars[0] = "Opel"

示例

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
cars[0] = "Opel"
println(cars[0])
// 现在输出 Opel 而不是 Volvo
自己试试 »

数组长度/大小

要找出数组有多少个元素,请使用 size 属性

示例

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


检查元素是否存在

您可以使用 in 运算符检查数组中是否存在某个元素

示例

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
  println("It exists!")
} else {
  println("It does not exist.")
}
自己试试 »

遍历数组

在处理数组时,通常需要遍历所有元素。

您可以使用 for 循环遍历数组元素,您将在下一章中进一步学习它。

以下示例输出cars数组中的所有元素

示例

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


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.