js判断数组中是否包含某个元素
方法1:arr.indexOf(element):判断数组中是否存在某个值,如果存在,则返回数组元素的下标(第一个元素),否则返回-1;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
let a = fruits.indexOf("Apple")
console.log(a) // 2
方法2:array.includes(searcElement[,fromIndex]):判断数组中是否存在某个值,如果存在返回true,否则返回false;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
if(fruits.includes("Apple")){
console.log("存在")
}else {
console.log("不存在")
}
方法3:arr.find(callback[,thisArg]):返回数组中满足条件的第一个元素的值,如果没有,返回undefined;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
let result = fruits.find(item =>{
return item == "Apple"
})
console.log(result) // Apple
方法4:array.findIndex(callback[,thisArg]):返回数组中满足条件的第一个元素的下标,如果没有找到,返回-1
;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
let result = fruits.findIndex(item =>{
return item == "Apple"
})
console.log(result) // 2
方法5:for():遍历数组,然后 if 判断;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
for(v of fruits){
if(v == "Apple"){
console.log("包含该元素")
}
}
方法6:forEach
let fruits = ["Banana", "Orange", "Apple", "Mango"]
fruits.forEach((v)=>{
if(v == "Apple"){
console.log("包含该元素")
}
})
本文来自博客园,作者:叶子玉,转载请注明原文链接:https://www.cnblogs.com/knuzy/p/14832304.html