本文旨在深入探讨华为鸿蒙HarmonyOS Next系统(截止目前API12)的技术细节,基于实际开发实践进行总结。主要作为技术分享与交流载体,难免错漏,欢迎各位同仁提出宝贵意见和问题,以便共同进步。本文为原创内容,任何形式的转载必须注明出处及原作者。
ArkTS 提供了一套容器集,包括 Array、Map、Set 等类型,用于存储和管理数据。ArkTS 容器与 JavaScript 原生容器在行为上存在一些差异,需要开发者注意。
ArkTS 的 Array、Map、Set 等容器类型
- Array:ArkTS 的 Array 类型与 JavaScript 的 Array 类型类似,但有一些差异,例如不允许在遍历、访问过程中进行元素的增删改操作。
- Map:ArkTS 的 Map 类型与 JavaScript 的 Map 类型类似,但有一些差异,例如构造函数中必须提供一个初始值的构造函数,且不支持使用计算属性名称。
Set:ArkTS 的 Set 类型与 JavaScript 的 Set 类型类似,但有一些差异,例如不允许在遍历、访问过程中进行元素的增删改操作,且 Sendable 类和接口中不允许使用计算属性名称。
原生 API 与 ArkTS API 的差异点
原生 API ArkTS API Array.from collections.Array.from Array.slice collections.Array.slice Map.entries collections.Map.entries Map.keys collections.Map.keys Map.values collections.Map.values Set.add collections.Set.add Set.delete collections.Set.delete Set.has collections.Set.has ArkTS 容器在并发中的应用
ArkTS 容器可以安全地在并发实例间传递,避免了数据竞争问题。但是,ArkTS 容器并不是线程安全的,内部使用了 fail-fast 机制。因此,在并发环境中使用 ArkTS 容器时,需要使用异步锁机制保证容器的安全访问。
ArkTS 容器的创建与操作实例
以下是一个简单的示例,演示如何创建和操作 ArkTS 容器:
import { collections } from '@kit.ArkTS'; @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(async () => { // 创建 Array const arr = new collections.Array<number>(); arr.push(1); arr.push(2); arr.push(3); console.log(arr); // 输出: [1, 2, 3] // 创建 Map const map = new collections.Map<number, string>(); map.set(1, 'one'); map.set(2, 'two'); map.set(3, 'three'); console.log(map); // 输出: {1: "one", 2: "two", 3: "three"} // 创建 Set const set = new collections.Set<string>(); set.add('one'); set.add('two'); set.add('three'); console.log(set); // 输出: Set { "one", "two", "three" } }) .width('100%'); } .height('100%'); } }
这段代码定义了一个名为
Index
的组件,并在组件中显示了一条文本消息 "Hello World"。点击按钮会创建 Array、Map 和 Set 容器,并输出容器的内容。ArkTS 容器与原生 API 对比表
原生 API | ArkTS API | 差异点 |
---|---|---|
Array.length | collections.Array.length | 不允许设置 length |
Array.pop | collections.Array.pop | 不允许在遍历、访问过程中进行元素的操作 |
Array.push | collections.Array.push | 不允许在遍历、访问过程中进行元素的操作 |
Array.concat | collections.Array.concat | 不允许在遍历、访问过程中进行元素的操作 |
Map.new | collections.Map.create | 必须提供初始值 |
Map.entries | collections.Map.entries | 不支持 thisArg |
Map.keys | collections.Map.keys | 不支持 thisArg |
Map.values | collections.Map.values | 不支持 thisArg |
Set.add | collections.Set.add | 不允许在遍历、访问过程中进行元素的操作 |
Set.delete | collections.Set.delete | 不允许在遍历、访问过程中进行元素的操作 |
Set.has | collections.Set.has | 不支持 thisArg |
总结
通过以上介绍,您可以了解到鸿蒙系统中 ArkTS 容器与原生容器的差异,以及 ArkTS 容器在并发中的应用。希望本文能够帮助您掌握鸿蒙系统中的并发编程技术,并开发出更优秀的鸿蒙应用。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。