当前位置:网站首页>js判断数组中是否存在某个元素(四种方法)
js判断数组中是否存在某个元素(四种方法)
2022-07-05 12:56:00 【燕双鹰...】
法一:利用indexOf
不存在返回-1,存在返回第一次出现的索引
// js检查数组中是否包含某个元素
// 法一 indexOf
var arr = [100,20,50,58,6,69,36,45,78,66,45]
if(arr.indexOf(66)==-1){
console.log("不存在")
}else{
console.log("存在,索引是:",arr.indexOf(66))
}
法二:利用find
它的参数是一个回调函数,所有数组元素依次遍历该回调函数,直到找出第一个返回值为true的元素,然后返回该元素,否则返回undefined。
var arr = [100,20,50,58,6,69,36,45,78,66,45]
arr.find(function(value,index,arr){
if(value==45){
console.log("存在",index)
}
})
console.log(param)
查找45,find会找出所有存在的45以及索引
法三:利用some
some方法同样用于检测是否有满足条件的元素,如果有,则不继续检索后面的元素,直接返回true,如果都不符合,则返回一个false。
用法与find相似,只是find是返回满足条件的元素,some返回的是一个Boolean值,从语义化来说,是否包含返回布尔值更贴切。
let arr = [100,20,50,58,6,69,36,45,78,66,45]
// some
let result = arr.some(ele => ele === 45) //true
if (result) {
//do something...
};
console.log(result)
法四:includes
ES6新增的数组方法,用于检测数组是否包含某个元素,如果包含返回true,否则返回false,比较厉害的是,能直接检测NaN:
优点 就不用说了,最简单的做法没有之一,不用回调,不用复杂的写法,一个方法直接搞定。
缺点 是低版本浏览器支持不是很友好
let arr = [100,20,50,58,6,69,36,45,78,66,45,NaN]
// 法四
let flag = arr.includes(1100)
let flag1 = arr.includes(NaN)
console.log(flag,flag1)
推荐使用includes()方法,方便快捷,一步到位~
边栏推荐
- insmod 提示 Invalid module format
- Didi open source Delta: AI developers can easily train natural language models
- From the perspective of technology and risk control, it is analyzed that wechat Alipay restricts the remote collection of personal collection code
- UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xe6 in position 76131: invalid continuation byt
- Binder通信过程及ServiceManager创建过程
- Default parameters of function & multiple methods of function parameters
- 逆波兰表达式
- Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article
- 量价虽降,商业银行结构性存款为何受上市公司所偏爱?
- Setting up sqli lab environment
猜你喜欢
Datapipeline was selected into the 2022 digital intelligence atlas and database development report of China Academy of communications and communications
ABAP editor in SAP segw transaction code
《2022年中國銀行業RPA供應商實力矩陣分析》研究報告正式啟動
Concurrent performance test of SAP Spartacus with JMeter
RHCSA10
数据湖(七):Iceberg概念及回顾什么是数据湖
Write macro with word
阿里云SLB负载均衡产品基本概念与购买流程
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
你的下一台电脑何必是电脑,探索不一样的远程操作
随机推荐
Introduction aux contrôles de la page dynamique SAP ui5
单独编译内核模块
开发者,云原生数据库是未来吗?
#从源头解决# 自定义头文件在VS上出现“无法打开源文件“XX.h“的问题
Detailed explanation of navigation component of openharmony application development
Lb10s-asemi rectifier bridge lb10s
Word document injection (tracking word documents) incomplete
ABAP editor in SAP segw transaction code
量价虽降,商业银行结构性存款为何受上市公司所偏爱?
CloudCompare——点云切片
RHCSA10
RHCSA9
RHCSA1
Leetcode20. Valid parentheses
A small talk caused by the increase of sweeping
Compile kernel modules separately
STM32 and motor development (from architecture diagram to documentation)
Introduction to sap ui5 flexiblecolumnlayout control
RHCSA2
简单上手的页面请求和解析案例