概述
在一门编程语言中,数据类型是最基本的组成,ArkTs提供了多种数据类型用于常见业务开发。 由于ArkTs是Ts的超集,所以数据类型也是基于TypeScript而来,除了原始5种数据类型之外,还有一种对象类型,还有枚举和任意类型等十几种数据类型
ArkTs与Ts数据类型对比
| ArkTs | 含义 | Ts | 含义 |
|---|---|---|---|
| number | 数值 | number | 数值 |
| boolean | 布尔 | boolean | 布尔类型 |
| string | 字符串 | string | 字符串 |
| undefined | 一个未定义或不存在的值 | arr | 数组 |
| null | 空 | [] | 元组 |
| object | 对象 | enum | 枚举 |
| Symbol | 独一无二的值 | void | 用于标识方法返回值的类型 |
| bigint | 任意大的整数 | null | 表示对象值缺失 |
| enum | 枚举 | undefinded | 用于初始化变量为一个未定义的值 |
| any | 任意 | never | 其它类型(包括nul和undefined)的子类型,代表从不会出现的值。 |
| unknown | 未知类型 | any | 任意值 |
| void | 没有任何返回值的类型 | ||
| never | 永远不存在的类型 |
注意:Arkts中也包含数组和元组
下文介绍
number(数值)boolean(布尔值)string(字符串)对象类型object数值类型(number)数组元组
number(数值类型)
在Arkts中所有数值类型都是浮点数,通过number来进行声明,支持进制的表达方式
@State a: number = 3; //十进制
@State b: number = 0.3; //十进制
@State c: number = 0x6666; //十六进制
@State d: number = 0b1010; //二进制
@State e: number = 0o452313; //八进制
build() {
Row() {
Column() {
Text(`${this.a}`)
Text(`${this.b}`)
Text(`${this.c}`)
Text(`${this.d}`)
Text(`${this.e}`)
}.width('50%')
}.height('50%')
}
布尔类型(boolean)
boolean是编程中最基本的数据类型,是逻辑判断的基础。
boolean 有两种状态 true、false
true 代表为真值
false代表为假值
// 布尔值
@State flag: boolean = true;
build() {
Row() {
Column() {
if (this.flag)
Text("True")
else
Text("False")
}.width('100%')
}.height('100%')
}
字符串(string)
与其他的语言一样,使用string表示字符串,
程序会在Text等处于字符串设置文本的时候会有类型检查,必须使用string才可以通过语法检查。
// 字符串
@State message: string = 'Hello'
@State n: number = 10;
@State message2: string = `${this.message} ,this is string demo。${this.n}`
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text(`hello,this is string demo:${this.n}。`);
Text(this.message2)
}.width('100%')
}.height('100%')
}
对象型object
object 代表非原始类型数据。
// 对象型Object
@State v: object = { "hello": 123 }
build() {
Row() {
Column() {
Text(`${typeof this.v} - ${(this.v)}`)
Text(`${typeof this.v["hello"]} - ${(this.v["hello"])}`)
}.width('100%')
}.height('100%')
}
数组
数组是一系列数据的集合,大部分编程语言中都存在数组的概念
// 数组
@State ns1: number[] = [1, 2, 3];
@State ns2: Array<number> = [5, 6, 7];
build() {
Row() {
Column() {
ForEach(this.ns1, (item) => {
Text(`${item}`)
})
ForEach(this.ns2, (item) => {
Text(`${item}`)
})
}.width('100%')
}.height('100%')
}
元组
元组在ArkTS中表现为一个已知数量和类型的数组,各元素之间的类型不必相同。
// 元组
@State x: [string, number] = ["hello", 123];
build() {
Row() {
Column() {
Text(`${typeof this.x[0]} - ${this.x[0]}`)
Text(`${typeof this.x[1]} - ${this.x[1]}`)
}.width('100%')
}.height('100%')
}
总结
ArkTs是TypeScript的超集,一个变量,如果没有指定数据类型,它可以进行任何类型赋值,以最后一个赋值为最终结果。
let test //any
test = 0
test = "string"
test = true
console.log(test)
上面会打印true,在以后的开发中,要对数据进行类型限制,既方便与类型区分,也方便错误的检查,有利于让代码更加健壮。