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("包含该元素")
      }
    })
    
    你必须穷尽一生磨练技能,这就是成功的秘诀,也是让人家敬重的关键。
  • 相关阅读:
    java中的位运算符
    Servlet中的初始化参数、上下文参数、以及@Resource资源注入
    Servlet中文件上传的几种方式
    marquee标签的使用
    SpringBoot热部署的两种方式
    eclipse中安装lombok插件
    关于Servlet中的转发和重定项
    Cormen — The Best Friend Of a Man CodeForces 732B
    牛客小白月赛9之签到题
    Codeforces アンバランス / Unbalanced
  • 原文地址:https://www.cnblogs.com/knuzy/p/14832304.html
Copyright © 2011-2022 走看看