- typedArray.find:找到返回被找元素,找不到返回undefined
- typedArray.findIndex()是JavaScript中的内置函数,如果值满足函数中给定的条件,则该函数用于返回tyedArray中的索引,否则返回-1
typedarray.findIndex(callback)参数:它采用参数“callback”函数,该函数检查提供的条件满足的typedArray的每个元素。回调函数采用以下指定的三个参数:
- element:它是元素的值。
- index:它是元素的索引。
- array:遍历的是数组。
返回值:如果元素满足函数提供的条件,则返回数组中的索引;否则,返回-1。
findIndex 示例:
//示例1
const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5 ]
// 写法1
const index = arr.findIndex(item => {
return item > 2
})
console.log(index) // 2
// 写法2
const index = arr.findIndex(item => item > 2)
console.log(index) // 2
--------------------------------------------------------------------
//示例2
const findArr = [
{ name: '张三', no: '15' },
{ name: '李四', no: '10' },
{ name: '王五', no: '5' }
]
const fIndex = findArr.findIndex(({ name }) => name === '张三')
console.log(fIndex) // 0
const ffIndex = findArr.findIndex(({ name }) => name === '小付')
console.log(ffIndex);// -1
find示例:
//示例1
const arr = [
{
name: '张三',
age: 18
},
{
name: '李四',
age: 20
},
{
name: '王五',
age: 22
}
]
const val = arr.find(item => {
return item.age === 20
})
//换种写法
const val = arr.find(item => item.age === 20)
console.log(val)
// {
name: '李四',
age: 20
}
--------------------------------------------------------------------
//示例2
const findArr = [
{ name: '张三', no: '15' },
{ name: '李四', no: '10' },
{ name: '王五', no: '5' }
]
const ffind = findArr.find(({ name }) => name === '张三')
console.log(ffind) // { name: '张三', no: '15' }
const fffind = findArr.find(({ name }) => name === '小付')
console.log(fffind);// undefined
实际应用场景:就比如查找ID改变选中状态等等
<view class="todo-list" :class="{ 'todo--finish': item.checked }"
v-for="(item, index) in listData" :key="index" @click="finish(item.id)">
//点击列表表示已完成
finish (id) {
let index = this.list.findIndex((item) => item.id === id)
this.list[index].checked = !this.list[index].checked
},