ArkTS的基本语法
1.声明
ArkTS中的console.log()第一个参数只能打印string类型与js有所不同需要注意一下
static log(message: string, ...arguments: any[]): void;
let hi: string = 'hello';
hi = 'hello, world';
const hello: string = 'hello';
let hi1: string = 'hello';
let hi2 = 'hello, world';
2.类型
1.Number类型
2.Boolean类型
3.String类型
4.Void类型
(Object类型是所有引用类型的基类型。任何值,包括基本类型的值(它们会被自动装箱),都可以直接被赋给Object类型的变量 )
let x:object = new Number(1)
6.Array类型
enum ColorSet { Red, Green, Blue }
let c: ColorSet = ColorSet.Red;
console.log('枚举',JSON.stringify(c) )// 枚举 0
console.log('枚举',JSON.stringify(ColorSet) )
// 枚举 {"0":"Red","1":"Green","2":"Blue","Red":0,"Green":1,"Blue":2}
enum ColorSet { White = 0xFF, Grey = 0x7F, Black = 0x00 }
let c: ColorSet = ColorSet.Black;
console.log('枚举',c)
// 枚举 0(16进制)
class Cat {
name: string = 'cat';
// ...
}
class Dog {
name: string = 'dog';
// ...
}
class Frog {
name: string = 'frog';
// ...
}
type Animal = Cat | Dog | Frog | number;
// Cat、Dog、Frog是一些类型(类或接口)
let animal: Animal = new Cat();
animal = new Frog();
animal = 42;
// 可以将类型为联合类型的变量赋值为任何组成类型的有效值
含义:类型别名,顾名思义就是给某个类型起别名,之后就可以通过这个别名来使用类型啦。咱们开发中用到的一些内置类型就是通过 type 来定义的哦
// 定义类型别名
type IDType = string | number
// 使用类型别名
function printID(id:IDType ) {
console.log(id+'')
}
// 调用函数
printID(10)
printID('20')
@Entry
@Component
struct Page01_type {
@State message: string = 'Type类型别名';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
可以通过 typeof 运算符来获取类型,他返回的是一个字符串
// 前面 5 个可以正常获取到类型
console.log(typeof 123) // number
console.log(typeof '123') // string
console.log(typeof false) // boolean
console.log(typeof undefined) // undefined
function func() {
}
console.log(typeof func) // function
interface Person{
name:string
}
// 对象 数组 null 获取到的都是 object
const p: Person = {name:'jack'}
console.log(typeof null) // object
console.log(typeof [1, 2, 3]) // object
console.log(typeof p) // object
3.运算符
赋值运算符=,使用方式如x=y。
复合赋值运算符将赋值与运算符组合在一起,其中x op = y等于x = x op y。
复合赋值运算符列举如下:+=、-=、*=、/=、%=、<<=、>>=、>>>=、&=、|=、^=。
2.比较运算符
运算符 | 说明 |
=== | 如果两个操作数严格相等(对于不同类型的操作数认为是不相等的),则返回true。 |
!== | 如果两个操作数严格不相等(对于不同类型的操作数认为是不相等的),则返回true。 |
== | 如果两个操作数相等,则返回true。 |
!= | 如果两个操作数不相等,则返回true。 |
> | 如果左操作数大于右操作数,则返回true。 |
>= | 如果左操作数大于或等于右操作数,则返回true。 |
< | 如果左操作数小于右操作数,则返回true。 |
<= | 如果左操作数小于或等于右操作数,则返回true。 |
3.算术运算符
一元运算符为-、+、--、++。
二元运算符列举如下:
运算符 | 说明 |
+ | 加法 |
- | 减法 |
* | 乘法 |
/ | 除法 |
% | 除法后余数 |
4.位运算符
[这些日常开发很少用到]
运算符 | 说明 |
a & b | 按位与:如果两个操作数的对应位都为1,则将这个位设置为1,否则设置为0。 |
a | b | 按位或:如果两个操作数的相应位中至少有一个为1,则将这个位设置为1,否则设置为0。 |
a ^ b | 按位异或:如果两个操作数的对应位不同,则将这个位设置为1,否则设置为0。 |
~ a | 按位非:反转操作数的位。 |
a << b | 左移:将a的二进制表示向左移b位。 |
a >> b | 算术右移:将a的二进制表示向右移b位,带符号扩展。 |
a >>> b | 逻辑右移:将a的二进制表示向右移b位,左边补0。 |
5.逻辑运算符
运算符 | 说明 |
a && b | 逻辑与 |
a || b | 逻辑或 |
! a | 逻辑非 |
4.语句
1.if语句
switch (expression) {
case label1: // 如果label1匹配,则执行
// ...
// 语句1
// ...
break; // 可省略
case label2:
case label3: // 如果label2或label3匹配,则执行
// ...
// 语句23
// ...
break; // 可省略
default:
// 默认语句
}
condition ? expression1 : expression2
如果condition的为真值(转换后为true的值),则使用expression1作为该表达式的结果;否则,使用expression2。
4.For语句
使用for-of语句可遍历数组或字符串。示例如下:
for (let ch of 'a string object') {
/* process ch */
}
6.While语句
[非常简单不用举例]
如果condition的值为真值(转换后为true的值),那么statements语句会重复执行。示例如下:
do {
statements
} while (condition)
8.Break语句 :使用break语句可以终止循环语句或switch。
9.Continue语句 :continue语句会停止当前循环迭代的执行,并将控制传递给下一个迭代。
10.Throw和Try语句
5.函数
1.基本使用
//函数声明引入一个函数,包含其名称、参数列表、返回类型和函数体。
function add(x: string, y: string): string {
let z: string = `${x} ${y}`;
return z;
}
//?表示参数可以有也可以没有
function hello(name?: string) {
if (name == undefined) {
console.log('Hello!');
} else {
console.log(`Hello, ${name}!`);
}
}
//设置默认值
function multiply(n: number, coeff: number = 2): number {
return n * coeff;
}
multiply(2); // 返回2*2
multiply(2, 3); // 返回2*3
[js里面叫剩余参数,可以用argument直接接收但是这里不行]
function sum(...numbers: number[]): number {
let res = 0;
for (let n of numbers)
res += n;
return res;
}
sum(); // 返回0
sum(1, 2, 3); // 返回6
出于程序稳定性,以及运行性能考虑,在 ArkTS 中 ...(展开运算符) 只能用在数组上
(注:TS中 ... 数组和对象均可以使用 )
const numArr1: number[] = [1, 2, 3, 4]
const numArr2: number[] = [5, 6, 7]
// 合并到一起
const totalArr: number[] = [...numArr1, ...numArr2]
// 添加
const numArr3:number[] = [8,9,10]
const numArr4:number[] = [11,12,13]
// 将 numArr4 展开,传递给push
numArr3.push(...numArr4)
// 显式指定返回类型
function foo(): string { return 'foo'; }
// 推断返回类型为string
function goo() { return 'goo'; }
6.函数作用域
函数中定义的变量和其他实例仅可以在函数内部访问,不能从外部访问。
如果函数中定义的变量与外部作用域中已有实例同名,则函数内的局部变量定义将覆盖外部定义。
function join(x: string, y: string): string {
let z: string = `${x} ${y}`;
return z;
}
let x = join('hello', 'world');
console.log(x); //hello world
// 这是一个函数类型
type trigFunc = (x: number) => number
function do_action(f: trigFunc) {
//在ArkTS中函数的参数一定要限制
console.log('绝对值为',f(-1))
}
do_action(Math.abs); // 将函数作为参数传入
1.函数可以定义为箭头函数(要记得用变量接收)
let sum = (x: number, y: number): number => {
return x + y;
}
2.箭头函数的返回类型可以省略;省略时,返回类型通过函数体推断。
3.表达式可以指定为箭头函数,使表达更简短,因此以下两种表达方式是等价的:
let sum1 = (x: number, y: number) => { return x + y; }
let sum2 = (x: number, y: number) => x + y
(闭包的本质就是想在函数的外部拿到函数内部的值,这就需要返回一个函数,并在该函数的内部来调用需要拿到的变量从而进行锁定变量)
function f(): () => number {
let count = 0;
let g = (): number => { count++; return count; };
//我拿到了 count并把他返回出去从而就劫持了函数内部的count变量
return g;
}
let z = f();
z(); // 返回:1
z(); // 返回:2
2.函数的补充
作为实参传入另一个函数,并在该函数内被调用,用来完成某些任务的函数,成为回调函数
咱们用过很多次,比如:
Button.onClick(()=>{})
Scroll(){
}.onScroll(()=>{})
List(){
}.onScrollToIndex(()=>{})
Image()
.onAppear(()=>{});
[1,2,3].filter((item:number,index:number)=>{})
// ...
// 作为参数传递的函数 都是 回调函数
箭头函数在日常使用中,如果满足一些特定的条件,可以写的更为简洁
简写条件:
- 函数体只有一行,可以省略大括号
- 省略大括号时,如果有 return,也需要一起省略
- 参数只有一个,且不需要写类型,可以省略小括号
const numArr = [1, 2, 3, 4]
numArr.forEach((item: number) => {
console.log('', item)
})
const res = numArr.map((item: number) => {
return item * 2
})
const res2 = numArr.filter((item: number) => {
if (item > 2) {
return true
} else {
return false
}
})
-------------------简写形式
const numArr = [1, 2, 3, 4]
numArr.forEach(item => console.log('', item))
const res = numArr.map(item => item * 2)
const res2 = numArr.filter(item => item > 2)
调用自身的函数我们称之为递归函数。
基本用法
在某种意义上说,递归近似于循环。两者都重复执行相同的代码,并且两者都需要一个终止条件(避免无限循环,或者在这种情况下更确切地说是无限递归)。
// 没有退出条件的 递归函数--无限递归
function func(){
func()
}
//试一试
let num: number = 1
function printLog(num: number) {
console.log(`你好,第${num}次打印`)
// 递减
num--
// 退出条件
if (num > 1) {
printLog(num)
}
}
// 打印 10 次
printLog(10)