ArkTs基础(常见数据类型)

940 阅读2分钟

概述

在一门编程语言中,数据类型是最基本的组成,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其它类型(包括nulundefined)的子类型,代表从不会出现的值。
unknown未知类型any任意值
void没有任何返回值的类型
never永远不存在的类型

注意:Arkts中也包含数组和元组

下文介绍

  1. number(数值)
  2. boolean(布尔值)
  3. string(字符串)
  4. 对象类型object
  5. 数值类型(number)
  6. 数组
  7. 元组

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 有两种状态 truefalse  
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,在以后的开发中,要对数据进行类型限制,既方便与类型区分,也方便错误的检查,有利于让代码更加健壮。