鸿蒙 ——ArkTS(数组)

1.在数组头部增加 .unshift('')

2.在数组尾部增加 .push('')

let songs:string[] = ['天地龙鳞','却月']
//开头增加元素
songs.unshift('彩虹')
console.log('数组', songs)
console.log('数组长度',songs.unshift('花田错'))
//结尾新加元素
songs.push('海阔天空')
console.log('结尾加', songs)

3.删除数组头部 .shift()

4.删除数组尾部 .pop()

//1.从开头删除
console.log('开头删除的元素是,',songs.shift())
//2.结尾删除
console.log('结尾删除的是,',songs.pop())

5.任意位置添加/删除元素 .splice

let array:string[] = ['华为', '荣耀', '小米', 'vivo']
//任意位置删除或新增 .splice()
//1.新增(任意位置)
array.splice(2,0,'oppo') //向第二个位置插入元素 0代表不删除原来所在位的元素(若是1则要删除2位置的小米) 'oppo'指要插入的元素
console.log('第二个位置插入元素', array)
//2.删除
array.splice(2,2) //删除从位置2开始的两个元素,包括第二个位置
console.log('删除从位置2开始的两个元素', array)

6.遍历数组(简洁方式)

//遍历数组
for (let x of array){
  console.log(x)
}

简单案例练习

//案例1
let array_1:number[] = [22,3,44,55,80]
let sum:number = 0
for (let x of array_1){
  sum += x
}
console.log('累加和:',sum)

//案例2
let array_2:number[] = [22,3,44,55,80,10,11,5,-1]
let temp_1:number[] = []
for (let x of array_2){
  if (x >= 10){
    temp_1.push(x)
  }
}
console.log('大于等于10的元素:', temp_1)

//案例3
let array_3:number[] = [22,3,0,55,0,0,11,5,0]
let temp_2:number[] = []
for (let x of array_2){
  if (x != 0){
    temp_2.push(x)
  }
}

7.对象数组(直接上代码)

//1.约定接口(对象的类型)
interface student{
  stuId:number,
  stuName:string,
  stuAge:number,
  gender:string
}

let stuArr:student[] = [{stuId:1, stuName:'小明',stuAge:18,gender:'男'},
  {stuId:2, stuName:'小美',stuAge:20,gender:'女'},{stuId:3, stuName:'小张',stuAge:21,gender:'男'}]
//将对象转为字符串格式
console.log('学生数组', JSON.stringify(stuArr))
//访问数组成员
console.log("学生对象:", JSON.stringify(stuArr[1]))
//for of 遍历
for (let stu of stuArr){
  console.log(JSON.stringify(stu))
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值