zoukankan      html  css  js  c++  java
  • 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("包含该元素")
      }
    })
    
    你必须穷尽一生磨练技能,这就是成功的秘诀,也是让人家敬重的关键。
  • 相关阅读:
    python中的编码问题
    CVPR2018 Tutorial 之 Visual Recognition and Beyond
    hdu 1376 Octal Fractions
    hdu 1329 Hanoi Tower Troubles Again!
    hdu 1309 Loansome Car Buyer
    hdu 1333 Smith Numbers
    hdu 1288 Hat's Tea
    hdu 1284 钱币兑换问题
    hdu 1275 两车追及或相遇问题
    hdu 1270 小希的数表
  • 原文地址:https://www.cnblogs.com/knuzy/p/14832304.html
Copyright © 2011-2022 走看看