ES6中给数组扩展了不少方法, 文主要讲解ES6数组方法find()
与findIndex()
1. find()方法
该方法主要应用于查找第一个符合条件的数组元素,如果没有
符合条件的元素,返回值为undefined
。
let arr = [
{
id: 1,
name: 'zhangsan'
},
{
id: 2,
name: 'lisi'
}]
let result = arr.find(item => {
return item.id == 2
})
console.log(result)
返回结果如下:
2. findIndex()方法
findIndex() 方法返回符合条件的数组第一个
元素位置。如果没有
符合条件的元素返回 -1
let arr = [
{
id: 1,
name: 'zhangsan'
},
{
id: 2,
name: 'lisi'
}]
let result = arr.findIndex(item => {
return item.id == 2
})
console.log(result) // 1 返回的下标