ArkTs快速入门
ArkTS:是一门用于开发鸿蒙应用的编程语言。
认识和存储数据
编程语言的核心是处理数据。
三种常见数据类型:
String、number、boolean
存储数据:
变量:专门用户来存储数据的容器。
let 变量名: 类型 = 值
let title: String ='钵钵鸡'
//修改数据,单引号双引号都可以,修改的时候类型要对应
title = '一元一支'
console.log('字符串title',title)
let age:number = 18
//要注意number必须前面有字符串才能console
age = 19
console.log('年级',age)
let isLogin: boolean = true
isLogin = false
console.log('是否登录成功',isLogin)
软件中LivePreview可以自动开启和关闭,从
常量: 用来存储数据(不可变)
example:圆周率,公司名称(huawei)
const 常量名: 类型 = 值
const companyName : string = 'biubiu'
console.log('公司名',conpanyName)
console.log('PI:',PI)
命名规则:
1.只能包含数字 字幕 下划线 $ 不能以数字开头
2.不能使用内置关键字嚯保留字(let const)
3.严格区分大小写
let userName: string = "JohnDoe";
let _userID: number = 12345;
let $userBalance: number = 100.50;
let 1stUser: string = "Alice"; // 错误,不能以数字开头
let const: number = 10; // 错误,不能使用保留字
let user-name: string = "Bob"; // 错误,不能包含连字符
数组
数组:是一个容器,可以存储多个数据
let 数组名: 类型[] = [数据1,数据2,数据3,...]
let names : string[] = ['王师傅','小李','豆豆','毛毛']
// ------------------------------------------------
//使用数组字面量
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
// ------------------------------------------------
//使用Array泛型
let numbers: Array<number> = [1, 2, 3, 4, 5];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
// -------------------------------------------------
//访问和修改数组元素
let fruits: string[] = ["Apple", "Banana", "Cherry"];
// 访问元素
console.log(fruits[0]); // 输出: Apple
// 修改元素
fruits[1] = "Blueberry";
console.log(fruits[1]); // 输出: Blueberry
// ------------------------------------------------
数组方法
push() 和 pop()
//用于在数组末尾添加和删除元素。
let numbers: number[] = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4]
numbers.pop(); // [1, 2, 3]
// ------------------------------------------------
unshift() 和 shift()
//用于在数组开头添加和删除元素。
let numbers: number[] = [2, 3, 4];
numbers.unshift(1); // [1, 2, 3, 4]
numbers.shift(); // [2, 3, 4]
// ------------------------------------------------
concat()
//用于连接两个或多个数组。
let arr1: number[] = [1, 2];
let arr2: number[] = [3, 4];
let combined: number[] = arr1.concat(arr2); // [1, 2, 3, 4]
// ------------------------------------------------
slice()
用于提取数组的一部分
let numbers: number[] = [1, 2, 3, 4, 5];
//注意是左闭右开,按照下表
let subArray: number[] = numbers.slice(1, 3); // [2, 3]
// ------------------------------------------------
splice()
用于添加或删除数组中的元素。
let numbers: number[] = [1, 2, 3, 4, 5];
// 删除元素
numbers.splice(2, 1); // [1, 2, 4, 5]
// 添加元素
numbers.splice(2, 0, 3); // [1, 2, 3, 4, 5]
迭代数组
for 循环
let numbers: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// ------------------------------------------------
let numbers: number[] = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
// ------------------------------------------------
let numbers: number[] = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number);
});
// ------------------------------------------------
// ------------------------------------------------
综合示例
// 创建数组
let fruits: string[] = ["Apple", "Banana", "Cherry"];
// 访问和修改元素
console.log(fruits[0]); // 输出: Apple
fruits[1] = "Blueberry";
console.log(fruits[1]); // 输出: Blueberry
// 使用数组方法
fruits.push("Date");
console.log(fruits); // 输出: ["Apple", "Blueberry", "Cherry", "Date"]
fruits.pop();
console.log(fruits); // 输出: ["Apple", "Blueberry", "Cherry"]
fruits.unshift("Apricot");
console.log(fruits); // 输出: ["Apricot", "Apple", "Blueberry", "Cherry"]
fruits.shift();
console.log(fruits); // 输出: ["Apple", "Blueberry", "Cherry"]
// 连接数组
let moreFruits: string[] = ["Elderberry", "Fig"];
let allFruits: string[] = fruits.concat(moreFruits);
console.log(allFruits); // 输出: ["Apple", "Blueberry", "Cherry", "Elderberry", "Fig"]
// 提取子数组
let subArray: string[] = allFruits.slice(1, 3);
console.log(subArray); // 输出: ["Blueberry", "Cherry"]
// 添加和删除元素
allFruits.splice(2, 1, "Grapefruit");
console.log(allFruits); // 输出: ["Apple", "Blueberry", "Grapefruit", "Elderberry", "Fig"]
// 迭代数组
allFruits.forEach((fruit) => {
console.log(fruit);
});
函数
函数:是可以被重复使用的代码块
函数定义使用function
关键字,后跟函数名、参数列表和函数体。
1. 定义函数
function 函数名(){
函数体
}
2. 调用函数
函数名()
注意:先定义,后使用
示例:打印五角星
function star(){
console.log('*')
console.log('**')
console.log('***')
console.log('****')
console.log('*****')
}
//可以重复调用
star()
star()
star()
函数完整用法
根据我们传入不同的数据,进行处理,返回处理后的结果.
示例:用一个函数,实现下面的需求
传入价格和数量,返回计算的结果
1.苹果2元/斤,买了三斤,多少钱?
2.香蕉4元/斤,买了四斤,多少钱
function buy(price: number,num:number){
let result: number = price* num
return result
}
let apple: number = buy(2,3)
console.log('苹果',apple)
let banana:number = buy(4,4)
console.log('香蕉',banana)
注意点:形参和实参的数量要一致
基本函数
函数定义使用function
关键字,后跟函数名、参数列表和函数体。
function greet(name: string): string {
return `Hello, ${name}!`;
}
let message = greet("Alice");
console.log(message); // 输出: Hello, Alice!
匿名函数
匿名函数没有名称,可以赋值给变量或作为参数传递。
let add = function (x: number, y: number): number {
return x + y;
};
console.log(add(2, 3)); // 输出: 5
箭头函数
箭头函数是匿名函数的简写形式,特别适用于内联函数。
let 函数名 = () =>{
函数体
}
示例:
let star = () =>{
console.log('*')
console.log('**')
console.log('***')
console.log('****')
console.log('*****')
}
star()
let buy = (price: number, weight:number)=>{
return price * weight
}
let apple: number = buy(2,3)
let banana: number = buy(4,4)
let multiply = (x: number, y: number): number => {
return x * y;
};
console.log(multiply(2, 3)); // 输出: 6
函数参数
可选参数:使用?
定义可选参数。
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // 输出: Hello, Alice!
console.log(greet("Bob", "Hi")); // 输出: Hi, Bob!
默认参数:可以为参数提供默认值。
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Alice")); // 输出: Hello, Alice!
console.log(greet("Bob", "Hi")); // 输出: Hi, Bob!
剩余参数:使用...
语法定义剩余参数,表示函数可以接受不定数量的参数
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 输出: 6
console.log(sum(4, 5, 6, 7)); // 输出: 22
函数重载
函数重载允许同名函数根据不同的参数类型或数量实现不同的功能。
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x: any, y: any): any {
return x + y;
}
console.log(add(1, 2)); // 输出: 3
console.log(add("Hello, ", "World!")); // 输出: Hello, World!
高阶函数
高阶函数是指可以接受函数作为参数或返回函数的函数。
function operateOnNumbers(x: number, y: number, operation: (a: number, b: number) => number): number {
return operation(x, y);
}
let result = operateOnNumbers(2, 3, (a, b) => a + b);
console.log(result); // 输出: 5
综合示例
// 基本函数
function greet(name: string): string {
return `Hello, ${name}!`;
}
let message = greet("Alice");
console.log(message); // 输出: Hello, Alice!
// 匿名函数
let add = function (x: number, y: number): number {
return x + y;
};
console.log(add(2, 3)); // 输出: 5
// 箭头函数
let multiply = (x: number, y: number): number => {
return x * y;
};
console.log(multiply(2, 3)); // 输出: 6
// 可选参数
function greetOptional(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greetOptional("Alice")); // 输出: Hello, Alice!
console.log(greetOptional("Bob", "Hi")); // 输出: Hi, Bob!
// 默认参数
function greetDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greetDefault("Alice")); // 输出: Hello, Alice!
console.log(greetDefault("Bob", "Hi")); // 输出: Hi, Bob!
// 剩余参数
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 输出: 6
console.log(sum(4, 5, 6, 7)); // 输出: 22
// 函数重载
function addOverload(x: number, y: number): number;
function addOverload(x: string, y: string): string;
function addOverload(x: any, y: any): any {
return x + y;
}
console.log(addOverload(1, 2)); // 输出: 3
console.log(addOverload("Hello, ", "World!")); // 输出: Hello, World!
// 高阶函数
function operateOnNumbers(x: number, y: number, operation: (a: number, b: number) => number): number {
return operation(x, y);
}
let result = operateOnNumbers(2, 3, (a, b) => a + b);
console.log(result); // 输出: 5
对象
作用:用户描述一个物体的特征和行为
可以存储多个数据的容器
对象是用于存储具有键值对集合的复杂数据结构。对象可以包含属性和方法,属性是对象的变量,方法是对象的函数。
对象-定义和使用(创建对象)
let 对象名称: 对象结构类型 = 值
1.通过interface接口
2.定义对象并使用 (对象.访问)
举例:定义一个对象
1.定义接口哦
interface Person{
name: string
age: number
weight: number
}
2.基于接口,定义对象
let wsf:Person ={
name:'王师傅',
age: 18,
weight: 100
}
console.log('姓名',wsf.name)
console.log('年龄',wsf.age)
console.log('体重',wsf.weight)
对象-方法
方法作用:描述对象的具体行为
interface 接口名称 {
方法名: (参数:类型) => 返回值类型
}
interface Person{
sing: () => void
cook: (cook:string) => void
}
添加方法
let wsf: Person = {
sing.() =>{
console.log("唱首歌歌")
}
cook.(cook:string) =>{
console.log('来做个',cook)
}
}
wsf.sing()
wsf.cook('红烧肉')
对象字面量
使用对象字面量创建一个简单对象。
let person = {
name: "Alice",
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.name); // 输出: Alice
console.log(person.greet()); // 输出: Hello, my name is Alice
使用接口定义对象结构
使用接口来定义对象的结构。
interface Person {
name: string;
age: number;
greet(): string;
}
let person: Person = {
name: "Bob",
age: 25,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.name); // 输出: Bob
console.log(person.greet()); // 输出: Hello, my name is Bob
对象方法
添加方法
对象方法是定义在对象内部的函数。
let car = {
brand: "Toyota",
model: "Camry",
start: function() {
return `${this.brand} ${this.model} is starting`;
}
};
console.log(car.start()); // 输出: Toyota Camry is starting
对象的属性
访问和修改属性
可以使用点(.)或方括号([])语法访问和修改对象的属性。
let book = {
title: "1984",
author: "George Orwell"
};
// 访问属性
console.log(book.title); // 输出: 1984
// 修改属性
book.title = "Animal Farm";
console.log(book.title); // 输出: Animal Farm
// 使用方括号语法访问属性
console.log(book["author"]); // 输出: George Orwell
动态添加和删除属性
let user = {
name: "John"
};
// 动态添加属性
user.age = 28;
console.log(user.age); // 输出: 28
// 动态删除属性
delete user.age;
console.log(user.age); // 输出: undefined
对象解构(暂时比较难,可以忽略)
对象解构可以方便地提取对象的属性。
let employee = {
firstName: "Jane",
lastName: "Doe",
position: "Developer"
};
let { firstName, lastName, position } = employee;
console.log(firstName); // 输出: Jane
console.log(position); // 输出: Developer
对象的方法绑定(暂时比较难,可以忽略)
使用bind
方法可以绑定对象方法的this
上下文。
let person = {
name: "Alice",
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
let greet = person.greet;
console.log(greet()); // 输出: Hello, my name is undefined
let boundGreet = person.greet.bind(person);
console.log(boundGreet()); // 输出: Hello, my name is Alice
示例代码
以下是一个包含各种对象操作的综合示例:
interface Person {
name: string;
age: number;
greet(): string;
}
let person: Person = {
name: "Alice",
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.name); // 输出: Alice
console.log(person.greet()); // 输出: Hello, my name is Alice
// 动态添加和删除属性
person.age = 31;
console.log(person.age); // 输出: 31
delete person.age;
console.log(person.age); // 输出: undefined
// 对象解构
let employee = {
firstName: "Jane",
lastName: "Doe",
position: "Developer"
};
let { firstName, lastName, position } = employee;
console.log(firstName); // 输出: Jane
console.log(position); // 输出: Developer
// 方法绑定
let greet = person.greet;
console.log(greet()); // 输出: Hello, my name is undefined
let boundGreet = person.greet.bind(person);
console.log(boundGreet()); // 输出: Hello, my name is Alice
联合类型
联合类型是一种灵活的数据类型,他修饰的变量可以存储不同类型的数据
联合类型使用竖线(|
)分隔不同的类型。
举例:考试成绩可以是分数也可以是ABCDEF
let judge:number | string
judge = 100
judge = 'A'
联合类型还可以将变量值,约定在一组数据范围内进行选择
let gender: 'man' | 'woman' | 'secret'
基本示例
let value: number | string;
value = 42; // 正确
value = "Hello"; // 也正确
// value = true; // 错误,boolean 不是联合类型的一部分
使用联合类型
当使用联合类型时,需要考虑每种可能的类型。这可以通过类型保护(type guards)来实现。
类型保护
可以使用typeof
运算符来实现类型保护,以便在运行时检查类型并执行相应的操作。
function printValue(value: number | string) {
if (typeof value === "number") {
console.log(`The number is ${value}`);
} else if (typeof value === "string") {
console.log(`The string is ${value}`);
}
}
printValue(42); // 输出: The number is 42
printValue("Hello"); // 输出: The string is Hello
联合类型与接口
联合类型也可以用于接口。例如,定义一个可以是几种接口之一的类型。
interface Dog {
bark: () => void;
}
interface Cat {
meow: () => void;
}
type Pet = Dog | Cat;
function makeSound(pet: Pet) {
if ("bark" in pet) {
pet.bark();
} else if ("meow" in pet) {
pet.meow();
}
}
let myDog: Dog = { bark: () => console.log("Woof!") };
let myCat: Cat = { meow: () => console.log("Meow!") };
makeSound(myDog); // 输出: Woof!
makeSound(myCat); // 输出: Meow!
联合类型与数组
可以定义一个数组,其元素可以是多种类型之一。
let array: (number | string)[] = [1, "two", 3, "four"];
array.forEach(item => {
if (typeof item === "number") {
console.log(`Number: ${item}`);
} else if (typeof item === "string") {
console.log(`String: ${item}`);
}
});
联合类型示例
以下是一个包含各种联合类型用法的综合示例:
// 基本联合类型
let value: number | string;
value = 42; // 正确
value = "Hello"; // 也正确
// 使用联合类型的函数
function printValue(value: number | string) {
if (typeof value === "number") {
console.log(`The number is ${value}`);
} else if (typeof value === "string") {
console.log(`The string is ${value}`);
}
}
printValue(42); // 输出: The number is 42
printValue("Hello"); // 输出: The string is Hello
// 联合类型与接口
interface Dog {
bark: () => void;
}
interface Cat {
meow: () => void;
}
type Pet = Dog | Cat;
function makeSound(pet: Pet) {
if ("bark" in pet) {
pet.bark();
} else if ("meow" in pet) {
pet.meow();
}
}
let myDog: Dog = { bark: () => console.log("Woof!") };
let myCat: Cat = { meow: () => console.log("Meow!") };
makeSound(myDog); // 输出: Woof!
makeSound(myCat); // 输出: Meow!
// 联合类型与数组
let array: (number | string)[] = [1, "two", 3, "four"];
array.forEach(item => {
if (typeof item === "number") {
console.log(`Number: ${item}`);
} else if (typeof item === "string") {
console.log(`String: ${item}`);
}
});
枚举类型
枚举类型是一种特殊的数据类型,约定变量只能在一组数据范围内选择
可以使用enum
关键字来定义枚举。每个枚举成员都有一个值,默认情况下,这些值从0开始递增。
1定义枚举类型
2使用枚举类型,约束变量
举例:利用枚举类型,给变量设置主色
enum ThemeColor{
Red = '#ff0f29'
Orange = '#ff7100'
Green = '#30b30e'
}
let color: ThemeColor = ThemeColor.Red
基本示例
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // 输出: 0 因为你没有给值,所以默认就是出来的就是顺序
在这个示例中,Direction
枚举有四个成员:Up
、Down
、Left
和Right
,其值分别是0、1、2和3。
使用自定义值
可以为枚举成员指定自定义的数值。
enum Status {
Success = 200,
NotFound = 404,
ServerError = 500
}
let responseStatus: Status = Status.Success;
console.log(responseStatus); // 输出: 200
反向映射(可以忽略,后期需要理解)
在TypeScript中,枚举不仅可以通过名称访问值,还可以通过值访问名称。
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Left;
console.log(move); // 输出: 2
console.log(Direction[move]); // 输出: Left
字符串枚举
枚举成员的值也可以是字符串。
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let color: Color = Color.Green;
console.log(color); // 输出: GREEN
异构枚举
枚举可以包含混合的字符串和数字成员,但这种用法应谨慎使用。
enum MixedEnum {
No = 0,
Yes = "YES"
}
let answer: MixedEnum = MixedEnum.Yes;
console.log(answer); // 输出: YES
枚举示例
以下是一个综合示例,展示了如何在ArkTS中使用枚举:
// 定义基本枚举
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // 输出: 0
// 使用自定义值
enum Status {
Success = 200,
NotFound = 404,
ServerError = 500
}
let responseStatus: Status = Status.NotFound;
console.log(responseStatus); // 输出: 404
// 反向映射
let direction: Direction = Direction.Left;
console.log(direction); // 输出: 2
console.log(Direction[direction]); // 输出: Left
// 字符串枚举
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let color: Color = Color.Blue;
console.log(color); // 输出: BLUE
// 异构枚举
enum MixedEnum {
No = 0,
Yes = "YES"
}
let answer: MixedEnum = MixedEnum.Yes;
console.log(answer); // 输出: YES
使用枚举的好处
- 增强可读性:枚举使代码更加语义化,比使用数字或字符串常量更具可读性。
- 减少错误:使用枚举可以减少魔法数(magic numbers)和硬编码字符串,从而减少错误。
- 类型安全:枚举提供了额外的类型检查,帮助在编译时捕获错误。