方法1:arr.indexOf(element):判斷數(shù)組中是否存在某個值,如果存在,則返回數(shù)組元素的下標(第一個元素),否則返回-1;
let fruits = ["Banana","Orange","Apple","Mango"]
let a = fruits.indexOf("Apple")
console.log(a)// 2
方法2:array.includes(searcElement[,fromIndex]):判斷數(shù)組中是否存在某個值,如果存在返回true,否則返回false;
let fruits = ["Banana", "Orange", "Apple", "Mango"]
if(fruits.includes("Apple")){
console.log("存在")
}else {
console.log("不存在")
}
方法3:arr.find(callback[,thisArg]):返回數(shù)組中滿足條件的第一個元素的值,如果沒有,返回undefined;
let fruits = ["Banana","Orange","Apple","Mango"]
let result = fruits.find(item=>{
????return item =="Apple"
})
console.log(result)// Apple
方法4:array.findIndex(callback[,thisArg]):返回數(shù)組中滿足條件的第一個元素的下標,如果沒有找到,返回-1;
let fruits = ["Banana","Orange","Apple","Mango"]
let result = fruits.findIndex(item=>{
????return item =="Apple"
})
console.log(result)// 2
方法5:for():遍歷數(shù)組,然后 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("包含該元素")?
????}
})