[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
法一:利用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()方法,方便快捷,一步到位~