鸿蒙数组常用方法

755 阅读1分钟

image.png

let names: string[] = ['小红', '小明', '大强']
 
// 1. 查找
console.log('查找姓名', names[0])
 
// 2. 修改
names[1] = 'Jack'
console.log('names数组修改', names)
 
// 3.push():结尾新增
names.push('lily', '大壮')
console.log('数组names', names)
 
// 4.unshift(): 开头新增
names.unshift('Jack')
console.log('数组names push+unshift', names)
 
// 5.pop(): 结尾删除
names.pop()
 
// 6.shift(): 开头删除
names.shift()
 
console.log('数组names pop+shift', names)
 
// 7.指定位置增删元素
names.splice(1, 1, 'jack')
 
console.log('数组names splice', names)

image.png

image.png

//数组
const foods = ['西瓜', '苹果', '桃子', '香蕉', '苹果', '桃子']
 
//Indexof
const indexofuse = foods.indexOf('西瓜')
console.log('indexofuse', indexofuse)
 
//findIndex
const findindexuse = foods.findIndex(item => item === '桃子')
console.log('findindexuse', findindexuse)
 
//find
const finduse = foods.find(item => item === '香蕉')
console.log('finduse', finduse)

image.png

forEach方法、map 方法、filter 方法

这三个方法放到一起,是因为它们都会遍历所有的元素,其中ForEach是没有返回值的,所以直接输出结果,map可以理解成按照指定的条件重组成一个新数组,filter就是过滤筛选,只保留符合条件的元素,示例代码如下:

// 接口
interface Fruit {
  id: number
  name: string
  title: string
}
 
// 数组
const arr: Fruit[] = [
  { id: 1, name: '西瓜', title: '喝西北风' },
  { id: 2, name: '苹果', title: '苹苹淡淡' },
  { id: 3, name: '桃子', title: '桃之夭夭' },
  { id: 4, name: '香蕉', title: '百感蕉集' },
]
 
//forEach使用
arr.forEach((item) => {
  console.log('foreach使用', item.id + 1, item.name + item.title)
})
 
//map使用
const mapArr = arr.map(item => item.name + item.title)
console.log('map使用', mapArr)
 
//filter使用
const filterArr = arr.filter(item => item.id > 2)
console.log('filter使用', JSON.stringify(filterArr))

image.png