ArkTS-语法基础

一、声明

变量声明 

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

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

常量声明

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

const hello: string = 'hello'

二、类型

Number类型

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

let intNum: number = 12
const floatNum: number = 0.2
const hexNum: number = 0xF7F7F7

if (isNaN(intNum)) {
  // 是否为非数字
}

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 isContain = str3.includes(str1)

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

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

const intNum = parseInt('12') // 12
const floatNum = parseFloat('3.1415') // 3.1415
const floatStr = floatNum.toFixed(2) // '3.14'

' every body '.replace(' ', '') // 'everybody'
' every body '.trim() // 'every body'

'every one'.startsWith('every') // true
'every one'.endsWith('one') // true

Array类型

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

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

const arr2: string[] = []
arr2.push('second')
arr2.indexOf('second') // 0
console.log(`length: ${arr2.length}`)

const isContain = arr2.includes('second')

const segments = 'm.baidu.com'.split('.') // ['m', 'baidu', 'com']
const host = segments.join('.') // 'm.baidu.com'

 Map类型

Map 类型,存储 key-value 键值对。

const map = new Map<string, string>()
map.set('name', 'Joy Chen')
const value = map['name'] // 'Joy Chen'
map.delete('name')

const keys = map.keys()
const values = map.values()

HashMap类型

HashMap 类型,存储 key-value 键值对, 先将 key 进行 hash 计算,得到 hash 值后再存储元素。

const hashMap = new HashMap<string, string>()
hashMap.set('name', 'Peter Li')
const value = hashMap['name'] // 'Peter Li'
hashMap.remove('name')

const isEmpty = hashMap.isEmpty()

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(obj => {
  // do something
})

arr.forEach((obj, idx) => {
  // do something
})

while语句

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

try-catch语句

try {
  // do something
} catch (e) {
  const error = e as Error
  console.log(`error: ${error.message}`)
}

四、运算符

三元运算符

const str = value ? value : ''

const str1 = value ?? ''

加/减运算符

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

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

可选链运算符

1)变量/属性的定义

class Article {
  title: string = '标题'
  summary?: string
  content: string | undefined

  init() {
    this.summary = '简介'
    this.content = '内容'
  }
  
  execute(hasSign: boolean) {
    this.title.length
    this.summary?.length
    this.content?.length

    let sign: string | undefined // 先声明
    if (hasSign) {
      sign = '署名' // 再赋值
    }
    const signLength = sign?.length ?? 0
  }
}

2)方法可选参数的定义

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

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

五、函数

函数声明/调用

function printInfo(title: string, content?: string) {
  console.log(`title: ${title}, content: ${content ?? ''}`)
}

printInfo('标题');
printInfo('标题', '内容')

函数类型 

通过 Type 声明函数的参数类型和返回值类型。

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)

Promise

Promise 是一种异步编程的解决方案,用于解决回调地狱(callback hell)问题,并使异步代码更具可读性和可维护性。

const promise: Promise<string> = new Promise((resolve, reject) => {
  resolve('success')
})
 
promise.then((res) => {
  console.log(res)
})

Promise 同时执行 resolve() 和 reject() 时,只能触发其中一个监听,也就是最终只会回调 ‘正常状态’ 或者 ‘异常状态’ 。

import { BusinessError } from '@ohos.base';

const promise: Promise<object> = new Promise((resolve, reject) => {
  if(isSuccess) {
    const result: object = new Object()
    result['code'] = 0
    result['message'] = 'success'
    resolve(result)
  } else {
    const error: BusinessError = {
      code: 201,
      name: 'Permission', 
      message: 'BussinessError 201: Permission denied.'
    }
    reject(error)
  }
})

promise.then((res) => {
  console.log(`result: ${res['message']}`)
}).catch((err: BusinessError) => {
  console.log(`error: ${err.message}`)
})

Promise 作为函数返回值的场景应用:获取 pushToken(直接调用 pushService 的接口)。

import { pushService } from '@kit.PushKit';
import { BusinessError } from '@ohos.base';

function getPushToken(): Promise<string> {
  return pushService.getToken()
}

getPushToken().then((token) => {
  console.log(`push_token: ${token}`)
}).catch((err: BusinessError) => {
  console.error(`error: ${JSON.stringify(err)}`)
})

Promise 作为函数返回值的场景应用:获取 pushToken(优先使用缓存数据,没有再调用 pushService 的接口)。

import { pushService } from '@kit.PushKit';
import { BusinessError } from '@ohos.base';

let pushToken: string | undefined

function getPushToken(): Promise<string> {
  return new Promise((resolve, reject) => {
    if (pushToken) {
      resolve(pushToken)
    } else {
      pushService.getToken().then((token) => {
        pushToken = token
        resolve(token)
      }).catch((err: BusinessError) => {
        reject(err)
      })
    }
  })
}

getPushToken().then((token) => {
  console.log(`push_token: ${token}`)
}).catch((err: BusinessError) => {
  console.error(`error: ${JSON.stringify(err)}`)
})

async/await

async/await 可以将 Promise 的编写方式从异步转为同步,不会造成同步阻塞。async 用于申明一个 function 是异步的,返回的是一个 Promise 对象,await 用于等待一个异步方法执行完成。

async function getCacheSize(): Promise<number> {
  try {
    const bunldeStats = await storageStatistics.getCurrentBundleStats()
    return bunldeStats.cacheSize
  } catch (e) {
    return 0
  }
}

getCacheSize.then((size) => {
  console.log(`cacheSize: ${String(size)}`)
}

六、类

类声明

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

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')

实例方法

class Car {
    execute() {
        // do something
    } 
}
 
const car = new Car()
car.execute()

Getter/Setter方法

class Car {
  private _name: string = ''
  private _price?: number
  
  set name(name: string) {
    this._name = name
  }
  
  get name(): string {
    return this._name
  }

  set price(price: number | undefined) {
    this._price = price
  }
  
  get price(): number | undefined {
    return this._price
  }

  execute() {
    this.name = 'BYD' // set
    console.log(this.name) // get
  }
}

类继承

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()

七、引用

导出

使用关键字 export 导出顶层的声明;未导出的声明名称被视为私有名称,只能在声明该名称的模块中使用。

// 常量
export const Version = '1.0.0' 

// 枚举
export enum Direction { ... }

// 接口
export interface PageInterface { ... }

// 类
export class BasePage { ... }

导入

使用关键字 import 导入声明,实现系统 API 与项目 Module 能力的调用。

import { Version, Direction, PageInterface, BasePage } from '../common/page/index';
import { Ability } from '@kit.AbilityKit';

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值