it编程 > 硬件开发 > arm开发

HarmonyOS Next 纯血星河版【六】【ArkTS语法】:数组的增删改查操作、判断和循环以及算元语句、条件渲染(淘宝购物车案例)、数组的遍历和数组对象的定义使用、ForEach遍历渲染的使用

75人参与 2024-08-06 arm开发

harmonyos next atkts语法

一、数组的操作

在这里插入图片描述

1. 数组 - 定义、查找、修改

在这里插入图片描述

1.1 定义一个数组
// 定义一个数组
let arr : string[] = ['张三', '李四', '王五', '赵六']
console.log('整个数组内容为;', arr)

运行效果如下:
在这里插入图片描述

1.2 通过索引查找数组元素
// 2. 通过下标访问指定的数组元素
console.log(arr[1])  // 李四   (注意,索引 从 0  开始)
1.3 通过索引修改 数组元素
// 3. 修改数组下标指定的元素
arr[0] = '数组'
console.log('修改后的数组内容为:', arr)

在这里插入图片描述

2. 数组 - 添加元素

在这里插入图片描述

3. 数组 - 删除元素

在这里插入图片描述

4. 数组 - 任意位置添加、删除

在这里插入图片描述

// splice方法,任意位置:删除
let arr1 : string[] = ['张三', '李四', '王五', '赵六']
arr1.splice(3, 1) // 从索引为 3 的元素处,开始删除,个数为 1
console.log('数组:',arr1)  //  张三,李四,王五


// splice方法,任意位置 :新增
arr1.splice(1, 0, '添加', '元素')  // 参数一: 起始索引   参数二: 操作的个   参数三: 添加的元素
console.log('arr1:', arr1)

6. 数组操作 – 总结

在这里插入图片描述

二、arkts 中的 语句 - 判断

在这里插入图片描述

1. if - 判断语句

1.1 if 分支
单分支

在这里插入图片描述

双分支

在这里插入图片描述

代码演示:
// if 语句的基本使用  (大家不考试,不需要分清楚单分支双分支,知道怎么执行,怎么用就好了)
let age : number = 19   // 现在十九了,以前 18 天天 写 十八岁
if (age > 18) {
  console.log('年龄分段', `年龄为:${age} , 您已成年!`)
} else {
  console.log('年龄分段', `年龄为:${age} , 您未成年!`)
}
// 运行结果:年龄分段 年龄为:19 , 您已成年!
1.2 判断语句 小结:

在这里插入图片描述

1.3 . 实际开发案例的使用

在这里插入图片描述

@entry
@component
struct arraydemocode {
  // 状态变量
  @state number : number = 1
  build() {
    column() {
      row({ space: 10}) {
        text('-').width(30).height(30).border({ width: 1, color: color.black}).fontsize(24).textalign(textalign.center).borderradius(15)
          .onclick( () => {
            // 如果 this.number 小于 1 ,不允许操作数据,否则允许
            if (this.number > 1) {
              this.number--
            } else {
              console.log('this.number(-)', '操作已经达到上限!!!')
            }
          })
        text(this.number.tostring()).fontsize(26)
        text('+').width(30).height(30).border({ width: 1, color: color.black}).fontsize(24).textalign(textalign.center).borderradius(15)
          .onclick( () => {
            // 如果 this.number 小于 1000 ,允许操作数据,否则禁止
            if (this.number < 1000) {
              this.number++
            } else {
              console.log('this.number(+)', '操作已经达到上限!!!')
            }
          })
      }
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }
}

1. 4 if判断 多分支语句

在这里插入图片描述

2. switch - 判断分支语句

在这里插入图片描述

3. 三元运算符

在这里插入图片描述

// 三目运算符
let number : number = 10
console.log('结果为:', number > 20 ? 'true' : 'false')  // 结果为: false

三 、条件渲染

在这里插入图片描述

1. 淘宝购物车案例

需求:商品购买完毕了,我们及时渲染对应的组件。
在这里插入图片描述

在这里插入图片描述

代码示例:
import { alertdialog } from '@ohos.arkui.advanced.dialog'

@entry
@component
struct taobaoshoppingcarttest {
  @state total : number = 100
  build() {
    column() {
      column () {
        text(`商品还剩下${this.total}件!`).textalign(textalign.center).fontweight(700).fontsize(20)
        row({ space: 10}) {
          button('买 1 件')
            .fontsize(14)
            .onclick( () => {
              if (this.total > 0) {
                this.total--
              }
            })
          button('买 5 件')
            .fontsize(14)
            .onclick( () => {
               if (this.total >= 5) {
                   this.total -= 5
               }
            })
          button('买 10 件').onclick(() => { if (this.total >= 10) {this.total -= 10} })
        }
        .margin({ top: 10})
      }
      .width('100%')
      .layoutweight(1)
      .backgroundcolor('#fcfcfc')
      .justifycontent(flexalign.center)
        if (this.total > 0) {
          row(){
            row({space: 10}) {
              column({space: 5}) {
                image($r('app.media.dianpu')).width(24).height(24).fillcolor(color.black)
                text('客服').fontsize(12)
              }
              column({space: 5}) {
                image($r('app.media.kefu')).width(24).height(24).fillcolor(color.black)
                text('客服').fontsize(12)
              }
              column({space: 5}) {
                image($r('app.media.gouwucheman')).width(24).height(24).fillcolor(color.black)
                text('购物车').fontsize(12)
              }
            }
            row() {
              button('加入购物车').fontsize(14).fontcolor(color.white).backgroundcolor('#ffc745')
                .width(110).margin({left: 5, right: 5})
              button('立即购买').fontsize(16).fontcolor(color.white).backgroundcolor('#fb0029').width(100)
            }.width(220)
        }
        .width('100%').height(100).padding(10).justifycontent(flexalign.spaceevenly)
        } else {
          column() {
            row() {
              row() {
                image($r('app.media.tongzhi')).width(20).height(20).fillcolor(color.red).margin({left: 5, right: 10})
                text('该商品暂时没有库存,看看相似商品吧').fontsize(12).fontcolor('#cf9a6d')
              }
              image($r('app.media.zhedie')).width(20).height(20).fillcolor(color.orange)
            }
            .width('100%')
            .height(50)
            .justifycontent(flexalign.spacebetween)
            .backgroundcolor('#fff9dc')
            .padding(5)
            row() {
              row({space: 10}) {
                column({space: 5}) {
                  image($r('app.media.dianpu')).width(24).height(24).fillcolor(color.black)
                  text('客服').fontsize(12)
                }.layoutweight(1)
                column({space: 5}) {
                  image($r('app.media.kefu')).width(24).height(24).fillcolor(color.black)
                  text('客服').fontsize(12)
                }.layoutweight(1)
                column({space: 5}) {
                  image($r('app.media.gouwucheman')).width(24).height(24).fillcolor(color.black)
                  text('购物车').fontsize(12)
                }.layoutweight(1)
              }
              .layoutweight(1)
              button('查看类似商品')
                .width(160).margin(10).backgroundcolor('#ffc745').fontsize(18)
            }
            .width('100%')
            .height(100)
          }.width('100%').height(150)
        }
    }
    .width('100%').height('100%')
    .justifycontent(flexalign.spaceevenly)
    }
}

四、arkts - 循环语句

while循环

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2. while - 练习题

在这里插入图片描述

// 需求1: 打印 1 - 100 的数字
let i : number = 1;
while (i <= 100) {
  console.log("需求1:", i)
  i++
}

console.log("-------------------------------------------")

// 需求2:打印 1 - 100 之间的偶数
let z : number = 1;
while (z <= 100) {
  if (z % 2 == 0) {
    console.log("需求2:", z)
  }
  z++
}

console.log("-------------------------------------------")

// 需求3:计算 1 - 10 内数字的累加和
let k : number = 1
let sum : number = 0
while (k <= 10) {
  sum += k
  k++
}
console.log("需求三:", sum)

for 循环

在这里插入图片描述

代码示例

在这里插入图片描述

for循环练习
// 使用 for 循环 求 1- 10 之间的值
let sum2 : number = 0
for (let i : number = 1; i <= 10; i++) {
  sum2 += i
}
console.log("sum2: ", sum2)

五、退出循环

在这里插入图片描述

六、遍历数组

1. for 循环遍历

在这里插入图片描述

数组中的 - length方法

2. for of 遍历

在这里插入图片描述

3. 遍历数组练习

在这里插入图片描述


/**
 * 遍历数组的练习
 */

// 需求1:求数组的累加和 [22, 3, 44, 55, 80]
let arr1 : number[] = [22, 3, 44, 55, 80]
let sum1 : number = 0
for (let item of arr1) {
  sum1 += item
}
console.log('需求1:', sum1)  // 204

console.log('------------------------------------------')

// 需求2:筛选数组中大于 10 的元素 ,将其收集到新的数组中并打印出来 [22, 3, 44, 55, 80]
let arr2 : number[] = [22, 3, 44, 55, 80]
let newarr : number[] = []
for (let item  of arr2) {
  if (item > 10 ) {
    newarr.push(item)
  }
}
console.log('newarr', newarr) // 22,44,55,80

console.log('------------------------------------------')

// 需求3:将数组中 不是 0 的元素 收集到新的数组中 [22, 3, 0, 55, 0, 0, 11, 5, 0]
let arr3 : number[] = [22, 3, 0, 55, 0, 0, 11, 5, 0]
let newarr2 : number[] = []
for (let item of arr3) {
  if (item != 0) {
    newarr2.push(item)
  }
}
console.log('newarr2', newarr2)    // 2 22,3,55,11,5

七、对象数组

在这里插入图片描述

/**
 * 对象数组
 */

// 1. 定义接口规范对象的创建
interface student {
  id : string,
  name : string,
  gender : string
  age : number
}

// 2. 遵循接口类型规范,创建对象
let studentarray : student[] = [
  {id: '001', name: '张三', gender: '男', age: 23},
  {id: '002', name: '李四', gender: '男', age: 24}
]

// 3. 使用数组对象,和 普通对象一样
// console.log('查看张三:', studentarray[0])  引用数据类型打印只能看到类型哦
console.log('查看张三', json.stringify(studentarray[0]))


// 4. 遍历数组对象,也是一样的,就是需要注意使用,需要调用方法转换数据处理哦
for (let item  of studentarray) {
  console.log('数据对象', json.stringify(item))
}

八、 foreach - 遍历控制渲染

在这里插入图片描述

在这里插入图片描述

@entry
@component
struct foreachitemdemo  {
  // 准备数据源,数据列表
  @state titles : string[] = ['电子产品','精品服饰','母婴产品','影音娱乐','海外旅游']
  build() {
    column() {
      // 使用 foreach 遍历数组渲染
      foreach(this.titles, (item : string, index) => {
          text(item).fontsize(18).fontcolor('#ffccaa').fontweight(700).width('100%').padding(10).textalign(textalign.center)
      })
    } .width('100%').height('100%').padding(10)
  }
}

大家知道他的参数和使用即可!然后项目中多练习,加油!后面章节我们提供一个阶段性案例哦!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

DevEco Studio No device 无法识别 usb 设备 - 鸿蒙

08-06

【愚公系列】2023年12月 HarmonyOS应用开发者基础认证(完美答案)

08-06

HarmonyOS开发 :Router 和 NavPatchStatck 如何实现跳转(传参)及页面回调

08-06

线性模型:AR、MA、ARMA、ARMAX、ARX、ARARMAX、OE、BJ等

08-06

PyCharm部分实用快捷键和插件

08-06

pycharm手动安装常用插件

08-06

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论