ArkTS-语法基础

一、声明

变量声明 

以关键字 let 开头的声明引入变量,该变量在程序执行期间可以具有不同的值。

let hi: string = 'hello';
hi = 'hello, world';

常量声明

以关键字 const 开头的声明引入只读常量,该常量只能被赋值一次。

const hello: string = 'hello';

二、类型

Number类型

number 类型覆盖了任何整数和浮点数。

let integer: number = 12;
const floast: number = 0.2;
const hexNum: number = 0xF7F7F7;

Boolen类型

boolean 类型由 true 和 false 两个逻辑值组成。

let success: boolean = true;
if (success) {
  // do something
}

String类型

string代表字符序列,可以使用转义字符来表示字符。

const str1 = "title";
const str2 = 'detail';
const str3 = str1 + ' ' + str2; 

const content = `content: ${str3}`;
console.log(content);

const value = ''
if (value) {
  // value为空字符,不会触发if条件
} 

Array类型

array类型是由可赋值给数组声明中指定的元素类型的数据组成的对象。

const arr1 = new Array<string>();
arr1.push('a');
arr1.pop();

const arr2: string[] = [];
arr2.push('b');
console.log(`length: ${arr2.length}`);

Object类型

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

1)定义对象属性,创建对象并赋值

interface Customer {
  name: string,
  age: number,
  job?: string,
  interest: string | undefined
}

class Demo {
  demo(): void {
    const peter: Customer = {
      name: 'Peter', 
      age: 27,
      interest: undefined
    };
    peter.job = 'engineer';

    this.test(peter);
  }

  test(arg: object): void {
    // do something
  }
}

2)直接创建对象并赋值

class Demo {
  demo(): void {
    const peter: object = new Object();
    peter['name'] = 'Peter'
    peter['age'] = 15
    peter['job'] = 'student'
    peter['interest'] = undefined

    this.test(peter);
  }

  test(arg: object): void {
    // do something
  }
}

Void类型

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

function getDeviceId(): void {
  // do somethind
}

Enum类型

enum枚举类型用于声明一组命名的常数。

// 声明
enum Direction {
  LEFT,
  RIGHT,
  TOP,
  BOTTOM
}

// 应用
const direction = Direction.LEFT

三、语句

if语句

if (condition) {
  // do something
}

switch语句

switch (type) {
  case 0: 
    // do something
    break;
  case 1:
  case 2: // 同时命中1和2
    // do something
    break; 
  default:
}

for语句

const arr: string[] = ['a', 'b', 'c', 'd', 'e']
for (let i=0; i<arr.length; i+=1) {
  const str = arr[i]
  if (str === 'd') {
    break
  }
  // do something
}
const arr: string[] = ['a', 'b', 'c', 'd', 'e']
for (let str of arr) {
  if (str === 'b') {
    continue
  }
  // do something
}
const arr: string[] = ['a', 'b', 'c', 'd', 'e']
arr.forEach(str => {
  // do something
})

while语句

while (condition) {
  // do something
}
do {
  // do something
} while (condition)

try-catch语句

try {
  // do something
} catch (e) {
  console.log(`error: ${e}`)
}

四、运算符

三元运算符

const str = value ? value : ''

const str1 = value ?? ''

加/减运算符

let i = 0
i += 1 // 等价与 i = i+1

let j = 10
j -= 1 // 等价与 j = j-1

可选链运算符

1)变量/属性的定义

let value1: string = 'abc'
value1.length

// value2和value3的命名方式相同
let value2?: string
value2?.length

let value3: string | undefined | null
value3?.length

2)方法可选参数的定义

// 可选参数必须放在必选参数之后
function execute(str1: string, str2?: string): string {
  return str1 + (str2 ?? '')
}

execute('a', 'b')
execute('a')

五、函数

函数调用

调用函数以执行其函数体。

function printParams(a: string, b: string, c?: string) {
  console.log(`a: ${a}, b: ${b}, c: ${c}`);
}

printParams('a', 'b');
printParams('a', 'b', 'c');

函数类型

函数类型通常用于定义回调。

type callBackFunc = (message: string) => number // 函数类型

function execute(callBack: callBackFunc) {
  const code = callBack('success');
  console.log(`code: ${code}`);
}

let callBack = (message: string) => {
  console.log(`message: ${message}`);
  retrun 0;
}
execute(callBack);

六、类

类声明

引入一个新类型,并定义其字段、方法和构造函数。

class Car {
  name: string = ''
  style: string = ''
  price?: number
  private identify?: string

  constructor() {
    this.execute();
  }

  execute() {
    const detail = `${this.name} ${this.style}`;
    console.log(detail);
  }
}

构造函数

1)不带参数

constructor() {
  // do something
}

2)带参数

constructor(name: string, style: string) {
  this.name = name;
  this.style = style;
  // do something
}

 3)调用时机

// 不带参数
let car1 = new Car() ;
car1.name = 'Tesla';
car1.style = 'Model 3';

// 带参数
let car1 = new Car('Tesla', 'Model 3');

Get/Set方法

class Car {
  name: string = ''
  price?: number
  
  setName(name: string) {
    this.name = name;
  }
  
  getName(): string {
    return this.name;
  }

  setPrice(price?: number) {
    this.price = price;
  }
  
  getPrice(): number | undefined {
    return this.price;
  }
}

类继承

class BydCar extends Car {
  Batterylife?: number

  constructor() {
    this.name = 'Byd';
  }

  execute() {
    super.execute();
    // do something
  }
}

接口定义

interface CarInterface {
  drive(): void
} 

接口继承

interface BydInterface extends CarInterface {
  automaticParking(): void
} 

 接口实现

class BydCar extends Car implements BydInterface {
  constructor() {
    this.name = 'Byd';
  }

  drive(): void {
    // drive 
  }

  automaticParking(): void {
    // automatic parking
  }
} 

静态属性

// 声明
class EventConstants {
  static readonly AVAILABLE    = true

  static readonly LOADD_EVENT  = 'onLoad'
  static readonly UNLOAD_EVENT = 'onUnload'
}

// 应用
const available = EventConstants.AVAILABLE

静态方法

// 声明
class DeviceUtils {
  static getDeviceName(): string {
    return 'Hua Wei Mate60'
  }
}

// 应用
const deviceName = DeviceUtils.getDeviceName()

本文参考于鸿蒙开发者联盟:ArkTS语言介绍

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/780364.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

知识社区在线提问小程序模板源码

蓝色的知识问答&#xff0c;问答交流&#xff0c;知识社区&#xff0c;在线提问手机app小程序网页模板。包含&#xff1a;社区主页、提问、我的、绑定手机&#xff0c;实名认证等。 知识社区在线提问小程序模板源码

**kwargs 字典解包传参的方式

字典解包传参 在Python中&#xff0c;****kwargs**是一种通过字典解包 (dictionary unpacking) 的方式进行参数传递的方式。它将一个字典的键值对解包并传递给函数的命名参数。 示例代码 kwargs实参: {name: "jordan", age: 18, score: [80, 85, 85]} get_info形…

U盘非安全退出后的格式化危机与高效恢复策略

在数字化时代&#xff0c;U盘作为数据存储与传输的重要工具&#xff0c;其数据安全备受关注。然而&#xff0c;一个常见的操作失误——U盘没有安全退出便直接拔出&#xff0c;随后再插入时却遭遇“需要格式化”的提示&#xff0c;这不仅让用户措手不及&#xff0c;更可能意味着…

windows内置的hyper-v虚拟机的屏幕分辨率很低,怎么办?

# windows内置的hyper-v虚拟机的屏幕分辨率很低&#xff0c;怎么办&#xff1f; 只能这么大了&#xff0c;全屏也只是把字体拉伸而已。 不得不说&#xff0c;这个hyper-v做的很烂。 直接复制粘贴也做不到。 但有一个办法可以破解。 远程桌面。 我们可以在外面的windows系统&…

科普文:构建可扩展的微服务架构设计方案

前言 微服务架构是一种新兴的软件架构风格&#xff0c;它将单个应用程序拆分成多个小的服务&#xff0c;每个服务都运行在自己的进程中&#xff0c;这些服务通过网络进行通信。这种架构的优势在于它可以提高应用程序的可扩展性、可维护性和可靠性。 在传统的应用程序架构中&…

minist数据集分类模型的训练

minist数据集训练 训练方法&#xff1a;利用pytorch来实现minist数据集的分类模型训练 训练模型如下图所示 模型代码&#xff1a; import torch from torch import nn from torch.nn import Flattenclass Net(nn.Module):def __init__(self):super().__init__()self.module …

grid布局下的展开/收缩过渡效果【vue/已验证可正常运行】

代码来自GPT4o&#xff1a;国内官方直连GPT4o <template><div class"container"><button class"butns" click"toggleShowMore">{{ showAll ? 收回 : 显示更多 }}</button><transition-group name"slide-fade&…

KDP数据分析实战:从0到1完成数据实时采集处理到可视化

智领云自主研发的开源轻量级Kubernetes数据平台&#xff0c;即Kubernetes Data Platform (简称KDP)&#xff0c;能够为用户提供在Kubernetes上的一站式云原生数据集成与开发平台。在最新的v1.1.0版本中&#xff0c;用户可借助 KDP 平台上开箱即用的 Airflow、AirByte、Flink、K…

14-35 剑和诗人9 - 普及 Agentic RAG

好吧&#xff0c;让我们直接进入正题——了解 Agentic RAG&#xff08;检索增强生成&#xff09;方法以及它如何彻底改变我们处理信息的方式。系好安全带&#xff0c;因为这将变得疯狂&#xff01; Agentic RAG 的核心在于为 RAG 框架注入智能和自主性。这就像对常规 RAG 系统…

阶段三:项目开发---搭建项目前后端系统基础架构:任务10:SpringBoot框架的原理和使用

任务描述 1、熟悉SpringBoot框架的原理及使用 2、使用IDEA创建基于SpringBoot、MyBatis、MySQL的Java项目 3、当前任务请在client节点上进行 任务指导 1、SpringBoot框架的选择和原理 2、MyBatis-Plus的选择和原理 3、使用IDEA创建基于SpringBootMyBatis-PlusMySQL的Jav…

PCIe驱动开发(1)— 开发环境搭建

PCIe驱动开发&#xff08;1&#xff09;— 开发环境搭建 一、前言 二、Ubuntu安装 参考: VMware下Ubuntu18.04虚拟机的安装 三、QEMU安装 参考文章&#xff1a;QEMU搭建X86_64 Ubuntu虚拟系统环境 四、安装Ubuntu 下载地址&#xff1a;https://old-releases.ubuntu.com…

QWidget窗口抗锯齿圆角的一个实现方案(支持子控件)2

QWidget窗口抗锯齿圆角的一个实现方案&#xff08;支持子控件&#xff09;2 本方案使用了QGraphicsEffect&#xff0c;由于QGraphicsEffect对一些控件会有渲染问题&#xff0c;比如列表、表格等&#xff0c;所以暂时仅作为研究&#xff0c;优先其他方案 在之前的文章中&#…

k8s_集群搭建_在主节点中加入node节点_k8s集群自恢复能力演示_token过期重新生成令牌---分布式云原生部署架构搭建016

然后安装好了master节点以后,我们再来看如何把node节点加入进来,可以看到 只需要执行,命令行中提示的命令就可以了 比如上面的 Your Kubernetes control-plane has initialized successfully!To start using your cluster, you need to run the following as a regular user:…

人脸识别课堂签到系统【PyQt5实现】

人脸识别签到系统 1、运用场景 课堂签到,上班打卡,进出门身份验证。 2、功能类别 人脸录入,打卡签到,声音提醒,打卡信息导出,打包成exe可执行文件 3、技术栈 python3.8,sqlite3,opencv,face_recognition,PyQt5,csv 4、流程图 1、导入库 2、编写UI界面 3、打…

商家店铺电商小程序模板源码

橙色通用的商家入驻&#xff0c;商户商家&#xff0c;商家店铺&#xff0c;购物商城&#xff0c;商家购物平台app小程序网页模板。包含&#xff1a;商家主页、优先商家、商品详情、购物车、结算订单、个人中心、优惠券、会员卡、地址管理等功能页面。 商家店铺电商小程序模板源…

100359.统计X和Y频数相等的子矩阵数量

1.题目描述 给你一个二维字符矩阵 grid&#xff0c;其中 grid[i][j] 可能是 X、Y 或 .&#xff0c;返回满足以下条件的子矩阵数量&#xff1a; 包含 grid[0][0]X 和 Y 的频数相等。至少包含一个 X。 示例 1&#xff1a; 输入&#xff1a; grid [["X","Y",…

算法刷题笔记 滑动窗口(C++实现,非常详细)

文章目录 题目描述基本思路实现代码 题目描述 给定一个大小为n ≤ 10^6的数组。有一个大小为k的滑动窗口&#xff0c;它从数组的最左边移动到最右边。你只能在窗口中看到k个数字。每次滑动窗口向右移动一个位置。以下是一个例子&#xff1a; 该数组为 [1 3 -1 -3 5 3 6 7]&…

leetcode 66. 加一

leetcode 66. 加一 题解 刚开始只是以为在最后一位上加一就可以了 &#xff0c; 没想到还有进位呢&#xff0c; 比如说9的话&#xff0c; 加上1就是10&#xff0c; 返回的数组就是[1. 0],把进位的情况考虑进去就可以了。 class Solution { public:vector<int> plusOne(…

Vue3+.NET6前后端分离式管理后台实战(二十八)

1&#xff0c;Vue3.NET6前后端分离式管理后台实战(二十八)

Raw Socket(一)实现TCP三次握手

实验环境&#xff1a; Windows物理机&#xff1a;192.168.1.4 WSL Ubuntu 20.04.6 LTS&#xff1a;172.19.32.196 Windows下的一个http服务器&#xff1a;HFS&#xff0c;大概长这个样子&#xff1a; 客户端就是Ubuntu&#xff0c;服务端就是这个…