菜单
×
   ❮   
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 提供支持