我们在工作中经常需要查找数组中是否存在某个元素
在这总结了几种方法,每种特性都不一样,可以根据业务需求来选择合适的
1.indexOf方法
元素存在数组中则返回所在下标, 不存在返回 -1
const arr = [1,2,3]
if(arr.indexOf(1) > -1){
console.log('1存在arr数组中')
}else{
console.log('1不存在arr数组中')
}
2.some方法
返回布尔值,若元素存在数组中返回true,不存在则返回false
需要注意的是,元素存在则不往下继续查找,数组较大的情况下可以提升性能
const arr = [1,2,3]
if(arr.some(res=>res===1)){
console.log('1存在arr数组中')
}else{
console.log('1不存在arr数组中')
}
3.find方法
返回存在的元素,若不存在直接返回undefined
const arr = [1,2,3]
if(arr.find(res=>res===1)){
console.log('1存在arr数组中')
}else{
console.log('1不存在arr数组中')
}
4.findIndex
返回存在的第一个元素的下标,不存在返回 -1
const arr = [1,2,3]
if(arr.findIndex(res=>res===1) > -1){
console.log('1存在arr数组中')
}else{
console.log('1不存在arr数组中')
}
5.includes
返回布尔值,判断元素是否存在于数组中
const arr = [1,2,3]
if(arr.includes(1)){
console.log('1存在arr数组中')
}else{
console.log('1不存在arr数组中')
}