通俗易懂:
find() 方法用于查找数组的每一项元素,当找到第一个符合条件的元素时,返回该元素,数组后面的值不再进行查找。
当如果没有符合条件的元素时返回 undefined
注意:find()不会对空数组进行查找,不执行空数组,也不会改变原数组。
基本语法:
array.find((cuurentVal, index, arr) => {
console.log(cuurentVal, index);
})
其中 currentVal是当前值,index是当前索引,arr是当前数组,其中当前值currentVal是必选值。
eg.1 查找数组中大于 12 的第一个元素
// eg.1 查找数组中大于 12 的第一个元素
const arr = [2,4,6,8,10,12,14,16]
const res1 = arr.find( item => item > 12)
console.log('res1:', res1); // res1: 14
console.log('res1---arr', arr); //不改变原数组 res1---arr (8) [2, 4, 6, 8, 10, 12, 14, 16]
eg.2 从数组对象中查找符合条件的对象
// eg.2 从数组对象中查找符合条件的对象
const userList = [
{name: '张三', age: 18},
{name: '李思', age: 21},
{name: '王玲', age: 22},
{name: '傻强', age: 22}
]
const res2 = userList.find( u => u.age === 22 )
console.log('res2:', res2); // res2: {name: '王玲', age: 22}
eg.3 当数组中没有符合条件的元素 --返回undefined
// eg.3 当数组中没有符合条件的元素 --返回undefined
const arr3 = [2,4,6,8,10]
const res3 = arr3.find(item => item < 0)
console.log('res3:', res3); // res3: undefined
eg.4 实际项目中可能遇到的场景:
// eg.4 实际项目中可能遇到的场景:
// 组件内的某数组数据和接口返回的数组数据,查找两个数组的某属性id相同的话,再判断是否有符合条件的属性,
// 再进行相关操作,如往组件内的数组里push接口返回的item。
// let res= {
// code: 0,
// msg: 'success',
// data: [
// {type: 1, goodsId: 1, name: '华为mate60', color: '星光银', XXXX: 'XXX'},
// { type: 1, goodsId: 2, name: '华为mate30', color: '星光银', XXXX: 'XXX' },
// { type: 2, goodsId: 3, name: '香蕉mate60', color: '星光银', XXXX: 'XXX' },
// { type: 2, goodsId: 4, name: '西瓜mate60', color: '星光银', XXXX: 'XXX' },
// { type: 2, goodsId: 5, name: '苹果mate60', color: '星光银', XXXX: 'XXX' },
// ]
// }
let dataList = res.data
this.allDataList.filter( i => {
let result = dataList.find( item => item.goodsId === i.id )
if(result.type && result.type !== 1){
this.productList.push(result)
}
} )