ArkTS基础语法
声明
变量声明
let声明的变量,可以改变其值
let hello:string='hello'
hello='hello world'
常量声明
const声明的常量,该常量只能被赋值一次,对常量重新赋值会报错
const hello:string='hello'
自动类型推断
ArkTS的数据类型必须在编译时确定,如果一个变量或常量的声明包含了初始值,则不需要显式的指定其类型,如以下两种示例都是有效的,两个变量都是string类型
let hello1:string='hello world'
let hello2='hello world'
空安全
有时声明变量时会存在不确定初始值的情况,在这类情况下,通常使用联合类型包含null值
let name:string|null
consle.log(`${name.length}`) // Error Message:Cannot read property length of null
1.使用if/else语句进行判空
if(name!=null){...}
2.使用空值合并表达式,??左边的值为null时会返回表达式右边的值
const res=name??''
3.使用?可选链,如果是null,运算符会返回undefined
let len=name?.length
类型
基本类型
number、boolean、string、null、undefined、bigint等
引用类型
Interface、Object、Array、Enum、Class、Function、Tuple
Interface接口可以用来定义对象的结构,描述对象的属性和方法
interface StudentType{
name:string;
age:number;
}
//可使用extends关键字对接口进行拓展,t添加新的属性
interface newStudentType extends AreaSize{
weight:number;
}
Object对象用于存储各种键值集合,可以通过构造函数或使用字面量的方式创建
let student:StudentType={
name:'Daxi',
age:'19'
}
Function通过函数调用执行特定任务的代码块
let newName:string='';
function changeName(student:StudentType):void{
newName=student.name
}
//箭头函数的返回类型可以省略,通过函数体判断
const changeName=(student:StudentType)=>{newName=student.name}
Array数组用于存储一系列的值的有序的集合
let student:Array<string>=['Daxi','Xiaozhou','Xiaoyi','Xiaohong']
Class类是一种特殊的对象类型,用来创建对象实例
class User{
name:string='Daxi';
id:number=9;
}
let user:User=new User()
Class类中的可见性修饰符包括:private,protected和public,默认可见性为public
Tuple元组是一种特殊的数组,用于表示固定数量和类型的元素组合
let tuple:[string,number,boolean];
tuple=['hello daxi',222,true]
Enum枚举定义一组待选项
enum Color{
Red,
Blue,
Green
}
let favoriteColor:Color=Color.Red
联合类型 Union
允许变量的值有多个类型
let luckyNo:number|string
类型别名 Type Aliases
允许给一个类型取一个别名,方便理解和复用
type Matrix=number[][] //定义一个二维数组类型
let arr:Matrix=[[1,2,3]]
语句
条件语句基于不同条件来执行不同的动作,根据判断条件的执行结果(true或false)来决定执行的代码块
let isHappy:Boolean=true;
if(isHappy){
console.log('work')
}else{
console.log('no work')
}
循环语句重复执行相同的一组语句
let students:string[]=['Daxi','Xiaozhou','Xiaoyi','Xiaohong'];
//for循环语句
for(let i=0;i<students.length;i++){
console.log(students[i])
}
//for...of
for(let student of students){
console.log(student)
}
ArkTs的基本组成
示例:

代码:

-
装饰器: 用于装饰类、结构、方法以及变量,并赋予其特殊的含义。如上述示例中@Entry、@Component和@State都是装饰器,@Component表示自定义组件,@Entry表示该自定义组件为入口组件,@State表示组件中的状态变量,状态变量变化会触发UI刷新。
-
UI描述:以声明式的方式来描述UI的结构,例如build()方法中的代码块。
-
自定义组件:可复用的UI单元,可组合其他组件,如上述被@Component装饰的struct Hello。
-
系统组件:ArkUI框架中默认内置的基础和容器组件,可直接被开发者调用,比如示例中的Column、Text、Divider、Button。
-
属性方法:组件可以通过链式调用配置多项属性,如fontSize()、width()、height()、backgroundColor()等。
-
事件方法:组件可以通过链式调用设置多个事件的响应逻辑,如跟随在Button后面的onClick()。
HarmonyOS NEXT-ArkTs基础语法解析

2186

被折叠的 条评论
为什么被折叠?



