【鸿蒙学习笔记】数据类型

官方文档:ArkTS语言介绍

目录标题

[代码总结]

声明变量

cpp 复制代码
let hi: string = 'hello';
let hi2 = 'hello, world';    // 自动类型推断

声明常量

cpp 复制代码
const hello: string = 'hello';

数据类型 缺:byte char

Number类型 short int long float double

cpp 复制代码
let n1 = 3.14;
let n2 = 3.141592;
let n3 = .5;
let n4 = 1e10;

function factorial(n: number): number {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}

Boolean类型 boolean

cpp 复制代码
let isDone: boolean = false;

String类型

cpp 复制代码
let s1 = 'Hello, world!\n';       // 由单引号(')括起来
let s2 = "this is a string";      // 由双引号(")括起来
let s3 = `The result is ${a}`;    // 反向单引号(`)括起来的模板字面量

Void类型

void类型用于指定函数没有返回值。

Object类型

Object类型是所有引用类型的基类型。

Array类型

cpp 复制代码
let names: string[] = ['Alice', 'Bob', 'Carol'];

Enum类型

cpp 复制代码
enum ColorSet { Red, Green, Blue }
let c: ColorSet = ColorSet.Red;

enum ColorSet { White = 0xFF, Grey = 0x7F, Black = 0x00 }
let c: ColorSet = ColorSet.Black;

Union类型

cpp 复制代码
type Animal = Cat | Dog | Frog | number

let animal: Animal = new Cat();
animal = new Frog();
animal = 42;

let animal: Animal = new Frog();
if (animal instanceof Frog) {
  let frog: Frog = animal as Frog;
  animal.leap(); // 结果:青蛙跳
  frog.leap();   // 结果:青蛙跳
}
animal.sleep (); // 任何动物都可以睡觉

Aliases类型

Aliases类型为匿名类型(数组、函数、对象字面量或联合类型)提供名称,或为已有类型提供替代名称

cpp 复制代码
type Matrix = number[][];
type Handler = (s: string, no: number) => string;
type Predicate <T> = (x: T) => Boolean;
type NullableObject = Object | null;
相关推荐
六月的雨__2 分钟前
二手物品交易小程序的设计
java·sql·学习·小程序
scl、5 分钟前
AI学习与实践6_AI解场景Agent应用预研demo
人工智能·学习·agent·rag
赛亚超22 分钟前
可视化学习之pytorch可视化工具visdom
学习
真果粒wrdms30 分钟前
【sqlite3】联系人管理系统
linux·c语言·数据库·经验分享·笔记·sqlite
神明木佑36 分钟前
js学习--隔行换色
前端·javascript·学习
淘尽红尘几多娇37 分钟前
雅思词汇及发音积累 2024.7.4
笔记
子殊1 小时前
昇思25天学习打卡营第十一天|SSD目标检测
学习·目标检测
spark-aixin2 小时前
昇思学习打卡-5-基于Mindspore实现BERT对话情绪识别
人工智能·学习·bert
龙的爹23332 小时前
论文翻译 | (DSP)展示-搜索-预测:为知识密集型自然语言处理组合检索和语言模型
人工智能·学习·语言模型·自然语言处理·nlp
~光~~3 小时前
IMU预积分资料整合
学习·imu预积分