js 判断数组中是否包含某个值

本文介绍了JavaScript中四种用于查找数组元素的方法:indexOf用于查找并返回值的索引,includes检查值是否存在并返回布尔值,find寻找满足条件的第一个元素,而findIndex则返回满足条件的第一个元素的索引。
摘要由CSDN通过智能技术生成

方式一:array.indexOf(searchvalue, start)

 判断数组中是否存在某个值,如果存在,则返回数组元素的下标,否则返回-1

参数描述
searchvalue必填。规定需检索的字符串值。
start可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string Object.length - 1。如省略该参数,则将从字符串的首字符开始检索。
const arr = [10, 20, 30, 40];
const index = arr.indexOf(30);
console.log(index); // 下标:2

方式二:array.includes(searchvalue, start)

判断数组中是否存在某个值,如果存在返回true,否则返回false

参数描述
searchvalue必需,要查找的字符串。
start可选,设置从那个位置开始查找,默认为 0
const arr = [10, 20, 30, 40];
const exists = arr.includes(30); // true
if (exists) {
    console.log("存在");
} else {
    console.log("不存在");
}

方法三:array.find(function(currentValue, index, arr),thisValue)

返回数组中满足条件的第一个元素的值,如果没有,返回undefined

 

参数描述
function(currentValue, index,arr)

必需。数组每个元素需要执行的函数。
函数参数:

参数描述
currentValue必需。当前元素
index可选。当前元素的索引值
arr可选。当前元素所属的数组对象

thisValue可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
const arr = [10, 20, 30, 40];
const result = arr.find(item => {
  return item > 20
});
console.log(result); // 30

方法四:array.findIndex(function(currentValue, index, arr), thisValue)

返回数组中满足条件的第一个元素的下标,如果没有找到,返回-1

参数描述
function(currentValue, index,arr)

必须。数组每个元素需要执行的函数。
函数参数:

参数描述
currentValue必需。当前元素
index可选。当前元素的索引
arr可选。当前元素所属的数组对象

thisValue可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
const arr = [10, 20, 30, 40];
const result = arr.findIndex(item => {
  return item > 20
});
console.log(result); // 2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web网页精选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值