鸿蒙 OS-03 ArkUI 循环控制-列表.List + ForEach

206 阅读1分钟

图片来源:黑马程序员 bz

最终效果图:

image.png

循环:

在 TypeScript 中,forEach 用于遍历数组或类数组对象的元素,而传统的 for 循环(通常称为 fori,其中 "i" 代表索引)用于更一般的迭代情况,包括遍历数组。下面将展示如何在 TypeScript 中使用这两种循环。

1- 使用 forEach 遍历数组

forEach 方法为数组的每个元素执行一次提供的函数。这是一个数组的方法,只能用于数组或类数组对象。

let array = ['a''b''c''d']; 
array.forEach((element, index) => {
console.log(`Element at ${index}${element}`); 
});

这段代码会输出:

Element at 0: a 
Element at 1: b 
Element at 2: c 
Element at 3: d

2- 使用传统的 for 循环(fori)遍历数组

传统的 for 循环通过索引来访问数组的每个元素。这种方式更加通用,可以用于多种不同的迭代情况。

let array = ['a''b''c''d']
for (let i0; i < array.length; i++) {
console.log(`Element at ${i}: ${array[i]}`); 
}

这段代码的输出同样是:

Element at 0: a 
Element at 1: b 
Element at 2: c 
Element at 3: d

跳转:

.onClick(() => {
  // router跳转
  router.pushUrl(//固定写法
    {
      url: this.r.url,
      params: {id: this.i}
    },
    router.RouterMode.Single,
    err => {
      if(err){
        console.log(`路由失败,errCode: ${err.code} errMsg:${err.message}`)
      }
    }
  )
})

列表页面 code

image.png 具体代码: image.png

keyGenerator 唯一表示,判断是否需要重新渲染。如果不配置这个参数,默认:index+数据内容。

interface ForEachInterface {
    /**
     * Set the value, array, and key.
     * @since 7
     */
    /**
     * Set the value, array, and key.
     * @form
     * @since 9
     */
    (arr: Array<any>, itemGenerator: (item: any, index?: number) => void, keyGenerator?: (item: any, index?: number) => string): ForEachInterface;
}

image.png 详细 UI

image.png

List:列表 UI

image.png

image.png