鸿蒙移动应用开发--ArkTS语法进阶实验

任务一 **:**使用"展开运算符 ..."对自行建立的两个数组实现合并。

1、定义两个数组:

  • 在代码中定义两个数组 array1 和 array2,分别包含一些元素。
  • 例如:array1 = [1, 2, 3] 和 array2 = [4, 5, 6]。

2、使用展开运算符合并数组:

  • 使用展开运算符 ... 将两个数组的元素展开并合并到一个新的数组 combinedArray 中。
  • 代码示例:let combinedArray = [...array1, ...array2];

3、输出合并后的数组:

  • 使用 console.log 输出合并后的数组,验证结果是否正确。
  • 预期输出:[1, 2, 3, 4, 5, 6]。

源代码

java 复制代码
// 任务一:合并数组
let array1 = [1, 2, 3]
let array2 = [4, 5, 6]
console.log('原始数组1:',(array1).toString())
console.log('原始数组2:',(array2).toString())
let combinedArray = [...array1, ...array2] // 使用展开运算符合并数组
console.log('合并数组:',(combinedArray).toString())// 输出:[1, 2, 3, 4, 5, 6]
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
    }
    .height('100%')
    .width('100%')

  }
}

运行截图:


任务二 **:**使用"剩余参数"实现多个(数量不限)整数相加求和。

1、定义求和函数:

  • 使用剩余参数 ...numbers 定义一个函数 sum,该函数接受任意数量的整数参数。
  • 例如:const sum = (...numbers: number[]): number => { ... };

2、实现求和逻辑:

  • 使用数组的 reduce 方法对传入的参数进行累加求和。
  • 代码示例:return numbers.reduce((acc, num) => acc + num, 0);

3、调用函数并输出结果:

  • 调用 sum 函数,传入多个整数参数,并使用 console.log 输出结果。
  • 例如:console.log(sum(1, 2, 3, 4, 5));

源代码:

java 复制代码
// 任务二:使用剩余参数实现求和
const sum = (...numbers: number[]): number => {
  return numbers.reduce((acc, num) => acc + num, 0);
};
console.log('剩余参数实现求和:',(sum(1, 2, 3, 4, 5)).toString()); // 输出:15
console.log('剩余参数实现求和:',(sum(10, 20, 30)).toString()); // 输出:60
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
    }
    .height('100%')
    .width('100%')

  }
}

运行截图:


任务三 **:**创建一个class 类,使用"extends"实现子类继承父类,使用"readonly""private""protected""public"这四个修饰符,体会类的访问权限。

1、定义父类:

  • 创建一个父类 Parent,包含以下成员:
    1. public 成员变量 name:可以在类外部访问。
    2. protected 成员变量 age:只能在类内部和子类中访问。
    3. private 成员变量 gender:只能在类内部访问。
    4. readonly 成员变量 role:只读属性,初始化后不可修改。
  • 定义构造函数初始化这些成员变量。
  • 定义 public 方法 displayInfo,用于输出基本信息。
  • 定义 protected 方法 displayProtectedInfo,用于输出受保护的信息。
  • 定义 private 方法 displayPrivateInfo,用于输出私有信息。

2、定义子类:

  • 创建一个子类 Child,继承父类 Parent。
  • 在子类中调用父类的构造函数,并尝试访问父类的成员变量和方法。
  • 定义一个 public 方法 displayChildInfo,用于调用父类的 public 和 protected 方法。

3、测试类的继承和访问权限:

  • 创建父类和子类的实例。
  • 调用父类和子类的方法,验证访问权限是否符合预期。
  • 使用 console.log 输出结果。

源代码:

java 复制代码
// 父类
class Parent {
  public name: string;
  protected age: number;
  private gender: string;
  readonly role: string;
  constructor(name: string, age: number, gender: string, role: string) {
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.role = role;
  }
  public displayInfo() {
    console.log(`Name: ${this.name}, Age: ${this.age}, Role: ${this.role}`);
  }
  protected displayProtectedInfo() {
    console.log(`Protected Info: ${this.age}`);
  }
  private displayPrivateInfo() {
    console.log(`Private Info: ${this.gender}`);
  }
}
// 子类
class Child extends Parent {
  constructor(name: string, age: number, gender: string, role: string) {
    super(name, age, gender, role);
  }
  public displayChildInfo() {
    this.displayInfo(); // 可以访问父类的 public 方法
    this.displayProtectedInfo(); // 可以访问父类的 protected 方法
    // this.displayPrivateInfo(); // 无法访问父类的 private 方法
  }
}
// 任务三:测试类的继承和访问权限
let parent = new Parent('John', 30, 'Male', 'Developer');
let child = new Child('Alice', 25, 'Female', 'Designer');
parent.displayInfo(); // 输出:Name: John, Age: 30, Role: Developer
child.displayChildInfo(); // 输出:Name: Alice, Age: 25, Role: Designer
// child.displayProtectedInfo(); // 错误:无法直接访问父类的 protected 方法
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
    }
    .height('100%')
    .width('100%')
  }
}

运行截图:

相关推荐
江城开朗的豌豆7 分钟前
JavaScript篇:自定义事件:让你的代码学会'打小报告'
前端·javascript·面试
Code_流苏12 分钟前
C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)
开发语言·c++·stl容器·课设·期末大作业·日历程序·面向对象设计
道剑剑非道38 分钟前
QT开发技术【ffmpeg + QAudioOutput】音乐播放器 完善
开发语言·qt·ffmpeg
武昌库里写JAVA40 分钟前
iview Switch Tabs TabPane 使用提示Maximum call stack size exceeded堆栈溢出
java·开发语言·spring boot·学习·课程设计
ai产品老杨1 小时前
减少交通拥堵、提高效率、改善交通安全的智慧交通开源了。
前端·vue.js·算法·ecmascript·音视频
lexiangqicheng1 小时前
JS-- for...in和for...of
开发语言·前端·javascript
smallluan1 小时前
JS设计模式(4):观察者模式
javascript·观察者模式·设计模式
我是老孙1 小时前
windows10 php报错
开发语言·php
粥里有勺糖1 小时前
视野修炼-技术周刊第122期 | 发光图片制作
前端·javascript·github
y102121041 小时前
Python训练营打卡Day42
开发语言·javascript·ecmascript