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("包含该元素")
      }
    })
    
    你必须穷尽一生磨练技能,这就是成功的秘诀,也是让人家敬重的关键。
  • 相关阅读:
    rn相关文档
    《浅谈我眼中的express、koa和koa2》好文留存+笔记
    (四)Spring 对DAO 的支持
    (三)Spring 之AOP 详解
    (二)Spring 之IOC 详解
    SVN文件上感叹号、加号、问号等图标的原因
    Windows平台下不同版本SVN对比
    eclipse中启动Genymotion模拟器的错误
    (一)问候Spring4
    (十一)Hibernate 高级配置
  • 原文地址:https://www.cnblogs.com/knuzy/p/14832304.html
Copyright © 2011-2022 走看看