js判断一个元素是否在数组中

1.比较传统的做法:

概述:  indexOf()方法返回给定元素能找在数组中找到的第一个索引值,否则返回-1。

复制代码
复制代码
var a=["1", "3", "2", "3", "0"];
      console.log(a.indexOf ('3'));//1
      console.log(a.indexOf (5,'0'));//-1
      console.log(a.indexOf ('0'));//4
      console.log(a.indexOf ('0',-5));//4
      console.log(a.indexOf ('3',-1));//-1
      console.log(a.indexOf ('3',-3));//3
      console.log(a.indexOf ('1',5));//-1
      console.log(a.indexOf (3));//-1
      console.log(a);//["1", "3", "2", "3", "0"]
复制代码
复制代码

2.今天发现有个函数比较好用

let arr = [1,2,3];
arr.includes(1) // true
arr.includes(5) //false
posted @ 2020-03-17 03:50  37点2度  阅读(503)  评论(0编辑  收藏  举报