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.今天發現有個函數比較好用spa

let arr = [1,2,3];
arr.includes(1) // true
arr.includes(5) //false
相關文章
相關標籤/搜索