鸿蒙开发之ArkTS数组
在鸿蒙(HarmonyOS)开发中,ArkTS 提供了对数组(Array)的完整支持,包括声明、初始化、操作和遍历等。以下是 ArkTS 中数组的详细用法和示例:
1. 数组的声明与初始化
基本语法
// 方式1:使用类型标注(推荐)
let numbers: number[] = [1, 2, 3];
let names: string[] = ["Alice", "Bob", "Charlie"];// 方式2:使用泛型(Array<T>)
let flags: Array<boolean> = [true, false, true];// 方式3:空数组(需指定类型)
let emptyArray: string[] = [];
2. 数组的常用操作
添加元素
let fruits: string[] = ["Apple", "Banana"];// push():末尾添加
fruits.push("Orange"); // ["Apple", "Banana", "Orange"]// unshift():开头添加
fruits.unshift("Mango"); // ["Mango", "Apple", "Banana", "Orange"]
删除元素
// pop():删除末尾元素
let lastFruit = fruits.pop(); // "Orange", fruits = ["Mango", "Apple", "Banana"]// shift():删除开头元素
let firstFruit = fruits.shift(); // "Mango", fruits = ["Apple", "Banana"]// splice():删除指定位置元素
fruits.splice(1, 1); // 从索引1开始删除1个元素,fruits = ["Apple"]
修改元素
let colors: string[] = ["Red", "Green", "Blue"];
colors[1] = "Yellow"; // ["Red", "Yellow", "Blue"]
数组长度
console.log(colors.length); //
3. 数组的遍历
for…of 循环
for (const fruit of fruits) {console.log(fruit); // 依次输出 "Apple", "Banana"
}
forEach 方法
fruits.forEach((fruit, index) => {console.log(`${index}: ${fruit}`); // "0: Apple", "1: Banana"
});
map 方法(返回新数组)
let lengths = fruits.map(fruit => fruit.length); // [5, 6]
filter 方法(过滤)
let longFruits = fruits.filter(fruit => fruit.length > 5); // ["Banana"]
4. 数组的解构与展开
解构赋值
let [first, second] = fruits; // first = "Apple", second = "Banana"
展开运算符(…)
let newFruits = [...fruits, "Cherry"]; // ["Apple", "Banana", "Cherry"]
5. 多维数组
// 二维数组
let matrix: number[][] = [[1, 2, 3],[4, 5, 6],[7, 8, 9]
];// 访问元素
console.log(matrix[1][2]); // 6
6. 鸿蒙开发中的实际应用
UI 组件中的数组
@Entry
@Component
struct TodoList {@State todos: string[] = ["Learn ArkTS", "Build App", "Publish"];build() {Column() {ForEach(this.todos, (todo) => {Text(todo).fontSize(20).margin(10);})}}
}
动态更新数组
addTodo() {this.todos.push("New Task"); // 触发 UI 重新渲染
}