
数组遍历查询相关方法
作者: 夜深了
分类: 前端开发小技巧
发布: 2024-04-20 06:46:41
更新: 2025-03-23 12:48:10
浏览: 119
数组遍历查询到方法有,find,some, every
1. find
- find查询符合条件的项并返回该项并停止后续遍历
- 没有符合条件返回undefined
- 空数组直接返回undefined
2. some
- some查询符合条件的项并返回true并停止后续遍历
- 未查询到符合条件的项返回false
- 空数组直接返回false
3. every
- every遍历数组每一项,所有项都符合条件返回true,否则返回false
- 空数组直接返回false
const arr = [
{
id: 1,
name: 'yang',
type: 1
},
{
id: 2,
name: 'zhi',
type: 1
},
{
id: 3,
name: 'hao',
type: 1
}
]
/**
* arr.find
* 1. 查询符合条件的并返回该项
* 2. 查询到符合条件的数据后停止后续遍历
* 3. 未查询到符合条件的某项,返回undefied
*/
const find = arr.find((item, i, arr) => {
return item.id === 2
})
/**
* arr.some
* 1. 查询符合条件项,符合返回 true 反之 false
* 2. 查询到符合条件的数据后,返回true后停止后续遍历
*/
const some = arr.some((item, i, arr) => {
return item.id === 2
})
/**
* arr.every
* 1. 查询符合条件项,所有条件都符合 返回true 反之返回false
* 2. 查询到不符合条件项数据,返回false并停止后续遍历
*/
const every = arr.every((item, i, arr) => {
return item.type === 1
})