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

方式一: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

猜你喜欢

转载自blog.csdn.net/qq_43770056/article/details/129005077