【05】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-条件渲染+if/switch判断与for/while循环(附计数器、京东加购案例)

 序言:

本文详细介绍了ArkTs语言中的数组、if单双多分支判断、switch判读、while循环、for循环并给出相应的具体案例和实现代码,附有综合案例京东购物的加购。

笔者也是跟着B站黑马的课程一步步学习,学习的过程中添加部分自己的想法整理为笔记分享出来,如有代码错误或笔误,欢迎指正。

B站黑马的课程链接:鸿蒙课程介绍_哔哩哔哩_bilibili

 往期笔记:

【01】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-ArkTs基础语法与界面开发基础

【02】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-界面进阶与布局排布(附QQ登陆、得物、京东登陆综合案例+代码)

【03】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-更多布局(弹性/层叠)方式与界面开发综合(附飞狗卡片+B站卡片案例+实战开发支付宝界面+代码)

【04】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-ArkTs进阶运算符+状态管理(附综合案例美团购物车) 

目录

一.数组

二.语句-if

三.语句-switch

四.语句-三元条件表达式

五.条件渲染

六.京东购物车加购案例

七.语句-循环语句

八.对象数组

九.ForEach-渲染控制


一.数组

1.数组的操作

主要针对数组中的数据进行查找、修改、增加和删除

操作

语法

查找

数组名[下标]、数组名.length

修改

数组名[下标]=新值

增加

数组名.push(数据1,数据2,...)、

数组名.unshift(数据1,数据2,...()

删除

数组名.pop()、数组名.shift()

任意位置增加或删除

数组名.splice(操作的起始位置,删除的个数,新增1,新增2,...)

代码示意:

//1.定义数组
let names:string[] = ['刘小备','吕小布','张大飞','牛大马','飞飞鱼']
console.log('整个数组',names)


//2.数组取值
console.log('数组取值',names[1])
console.log('数组长度',names.length)


//3.数组修改
names[2]='赵小云'
console.log('修改数组',names[2])


//4.往数组添加元素
//4.1往开头加
names.unshift('雷电河马')
//4.2往结尾加
names.push('笨拙河马')
console.log('整个数组',names)


//5.删除数组元素
//5.1从开头删
names.shift()
//5.2从结尾删
names.pop()
console.log('整个数组',names)


//6 任意位置添加/删除数组元素
//6.1删除
names.splice(2,2)
console.log('整个数组',names)
//6.2新增
names.splice(1,0,'飞天河马','彩虹河马')
console.log('整个数组',names)

二.语句-if

语句概念:一段可以执行的代码,是一个行为(num=a+b)

表达式概念:可以被求值的代码,并将其计算出一个结果(1+1、3*5、3>2)

语句执行结构:

1.if分支语句

if分支语句:根据逻辑条件不同,执行不同语句

if (逻辑条件){
  条件成立执行代码
}
else {
  条件不成立执行代码
}
→小括号条件结果为true,则执行大括号里面的代码

→小括号结果不是布尔类型时,会类型转换为布尔值

代码实例:

//分支语句if
let brother:number = 30
let sister:number = 118
function score(num:number){
  if(num>80){
    console.log('考试优秀,带你去游乐园')
  }
  else {
    console.log('考试不及格,给我去写检讨')
  }
}
score(brother)
score(sister)

2.if计数器案例

@Entry
@Component
struct Index {
@State num:number=0
  build() {
    Row(){
      Text('-')
        .border({
          width:1
        })
        .onClick(()=>{
          if(this.num==0){
            AlertDialog.show({
              message:'数字已经不可减少'
            })
          }
          else {
            this.num--
          }
        })
        .textAlign(TextAlign.Center)
        .layoutWeight(1)
        .height(100)
        .width('100%')


      Text(this.num.toString())
        .border({
          width:1
        })
        .textAlign(TextAlign.Center)
        .layoutWeight(2)
        .height(100)
        .width('100%')


      Text('+')
        .onClick(()=>{
          this.num++
        })
        .border({
          width:1
        })
        .textAlign(TextAlign.Center)
        .layoutWeight(1)
        .height(100)
        .width('100%')
    }
    .padding(10)

  }

}

3.if多分支

if多分支,可以解决多种分支的情况

/*分支语句if多分支
if(条件1){
  条件1成立执行的代码
}
else if(条件2){
  条件2成立执行的代码
}
else if(条件3){
  条件3成立执行的代码
}
else {
  条件都不成立执行的代码
}*/
代码示意:

let brother:number = 30
let sister:number = 95
function score(num:number){
  if(num>90){
    console.log('优秀')
  }
  else if (num>80){
    console.log('良好')
  }
  else if(num>60){
    console.log('及格')
  }
  else{
    console.log('差')
  }
}
score(brother)
score(sister)

三.语句-switch

switch分支一般用于精确匹配,不同的值执行不同的代码

语法:

switch (表达式){
  case 值1:
    与值1匹配执行的语句
    break
  case 值2:
    与值2匹配执行的语句
    break
  default :
    以上都为成功匹配执行的代码
}

代码示意:

let brother:string = '男'
let sister:string = '女'
let xiaoming:string = '外星人'
function sex(sex:string) {
  switch (sex) {
    case '男':
      console.log('鉴定为','男孩穷养')
      break
    case '女':
      console.log('鉴定为','女孩富养')
      break
    default:
      console.log('鉴定为','外星人天生地养')
  }
}
sex(brother)
sex(sister)
sex(xiaoming)

四.语句-三元条件表达式

语法:

条件?条件成立执行的表达式:条件不成立执行的表达式

代码示意:

let num1:number = 20
let num2:number = 55
num1>num2?console.log('num1比num2大'):console.log('num1比num2小')

五.条件渲染

条件渲染:使用if、else和else if,可基于不同状态渲染对应不同UI内容

代码示意:

@Entry
@Component
struct Index {
@State num:number=1
  build() {
  //计数器
    Column(){
      Row() {
        Text('-')
          .border({
            width: 1
          })
          .onClick(() => {
            if (this.num == 0) {
              AlertDialog.show({
                message: '数字已经不可减少'
              })
            } else {
              this.num--
            }
          })
          .textAlign(TextAlign.Center)
          .layoutWeight(1)
          .height(100)
          .width('100%')


        Text(this.num.toString())
          .border({
            width: 1
          })
          .textAlign(TextAlign.Center)
          .layoutWeight(2)
          .height(100)
          .width('100%')


        Text('+')
          .onClick(() => {
            this.num++
          })
          .border({
            width: 1
          })
          .textAlign(TextAlign.Center)
          .layoutWeight(1)
          .height(100)
          .width('100%')
      }
      .padding(10)




      Column(){
        if(this.num<18){
          Text('未成年,18岁以下')
            .fontSize(25)
        }else if(this.num<30){
          Text('青少年,18岁到30岁')
            .fontSize(25)
        }
        else{
          Text('老年人,30岁以上')
            .fontSize(25)
        }
      }
    }
  }
}

六.京东购物车加购案例

1.代码示意:

@Entry
@Component
struct Index {
  // 库存, 有库存 > 0
  @State count: number = 0  // 无库存


  build() {
    Column() {
      Column() {
        // 底部菜单
        Row({space: 10}) {
          // 左侧菜单
          Row() {
            Column({space: 5}) {
              Image($r('app.media.ic_dianpu'))
                .width(20)
              Text('店铺')
                .fontSize(10)
                .fontColor('#262626')
            }
            Column({space: 5}) {
              Image($r('app.media.ic_kefu'))
                .width(20)
                .fillColor('#666')
              Text('客服')
                .fontSize(10)
                .fontColor('#262626')
            }
            Column({space: 5}) {
              Image($r('app.media.ic_cart2'))
                .width(20)
                .fillColor('#666')
              Text('购物车')
                .fontSize(10)
                .fontColor('#262626')
            }
          }
          .layoutWeight(1)
          .justifyContent(FlexAlign.SpaceBetween)


          // 根据库存控制不同按钮的展示
          if (this.count > 0) {
            // 右侧按钮 -- 可以购买
            Row({space: 5}) {
              Button('加入购物车')
                .width(105)
                .height(40)
                .backgroundColor('#ffcc00')
                .fontSize(14)
                .fontWeight(600)
              Button('立即购买')
                .width(105)
                .height(40)
                .backgroundColor('#f92c1b')
                .fontSize(14)
                .fontWeight(600)
            }
          }
          else {
            // 右侧按钮 -- 不能购买
            Row() {
              Button('查看类似商品')
                .width(170)
                .height(40)
                .backgroundColor('#ffcc00')
                .fontSize(14)
                .fontWeight(600)
            }
          }
        }
        .width('100%')
        .height(60)
        .backgroundColor('#f7f7f7')
        .padding({left: 20, right: 10})


        // 消息提示:库存 <= 0 显示,否则隐藏
        if (this.count <= 0) {
          Row() {
            // 左侧
            Row({ space: 5 }) {
              Image($r('app.media.ic_lingdang'))
                .width(12)
                .fillColor('#de6a1c')
              Text('该商品暂时没有库存,看看相似商品吧')
                .fontSize(10)
                .fontColor('#de6a1c')
            }


            // 右侧
            Image($r('app.media.ic_shangjiantou'))
              .width(15)
              .padding(3)
              .fillColor('#d0662c')
              .backgroundColor('rgba(0,0,0,0.1)')
              .borderRadius(8)
          }
          .width('100%')
          .height(36)
          .backgroundColor('#fbf9da')
          .position({ x: 0, y: '-36' })
          .padding({ left: 20, right: 20 })
          .justifyContent(FlexAlign.SpaceBetween)
        }


      }
      .position({x:0,y:'100%'})
      .translate({y: '-100%'})
    }
    .width('100%')
    .height('100%')
    .padding({bottom:20})
    .backgroundColor('#f2f2f2')
  }
}

效果图:

七.语句-循环语句

1.while循环语句

作用:重复执行指定的一段代码。

语法:

while (条件){
  条件为真=>重复执行的代码
}

示意:

let i:number = 1
while (i<=18){
  console.log('小明已经'+i+'岁了')
  i++
}
console.log('小明在十八岁那年去世了')

2.for循环语句

作用:重复执行指定的一段代码。

for (初始值;条件;变化量){
  重复执行的代码
}

示意:

for (let jindu:number = 0;jindu<=100;jindu=jindu+10){
  console.log('蛋糕的制作已经完成了'+jindu+'%')
}

3.退出循环

作用:满足指定条件,可以退出循环

→break:终止整个循环

→continue:退出当前一次循环的执行,继续执行下一次循环

代码示意:

for (let num:number = 0;num<20;num++){
  if(num==8){
    console.log('数字增加到八,退出本次循环')
    continue
  }
  if (num==15){
    console.log('数字增加到15,结束本循环')
    break
  }
  console.log('按例执行num增加操作'+num)
}

4.遍历数组-for

遍历:将数组里面的每个数据,按顺序访问一遍

代码示意:

let names:string[] = ['刘小备','吕小布','张大飞','牛大马','飞飞鱼']
for (let i:number = 0;i<names.length;i++){
  console.log('数组内第'+i+'个数据为'+names[i])
}

5.遍历数组-for...of

语法:

for(let item of 数组名){}

→for...of:在...之中进行循环

→item:声明的一个变量,用来在循环的时候接受每一个数组元素

代码示意:

let names:string[] = ['刘小备','吕小布','张大飞','牛大马','飞飞鱼']
for(let item of names){
  console.log('数组数据'+item)
}

八.对象数组

代码示意:

//1.定义接口
interface Person{
  stuId:number
  name:string
  gender:string
  age:number
}
//2.基于接口构建对象
let p1:Person ={
  stuId:1,
  name:'小丽',
  gender:'女',
  age:12
}
//3.基于接口构建对象数组
let pArr:Person[]=[
  {stuId:1,name:'小丽',gender:'女',age:12},
  {stuId:2,name:'小怪',gender:'男',age:13},
  {stuId:3,name:'小黑',gender:'女',age:14},
  {stuId:4,name:'小菜',gender:'男',age:15}
]
console.log('人数组',pArr)
//对象不能在日志里直接打印,如果想在日志中打印,需要转成字符串格式
//JSON.stringify(复杂类型) 对象/数组
console.log('人数组',JSON.stringify(pArr))

//4.具体使用
console.log('小怪',pArr[1].name)
//5.支持遍历
for (let item of pArr){
  console.log('每一项',JSON.stringify(item))
}

九.ForEach-渲染控制

作用:ForEach可以基于数组的个数、渲染组件的个数(简化代码)

代码示意;

@Entry
@Component
struct Index {
  @State titles:string[] = ['电子产品','精品服饰','母婴产品','影音娱乐','海外旅游','自助河马']
  build() {
    Column(){
      ForEach(this.titles,(item:string,index:number)=>{
        Text(`${index + 1} ${item}`)
          .fontSize(24)
          .fontWeight(700)
          .fontColor(Color.Orange)
          .width('100%')
          .padding(15)
      })
    }
  }
}

感谢阅读。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值