JavaScript 中 如何判断一个元素是否在一个数组中

<script type="text/javascript">
    var arrList=['12','qw','q','v','d','t'];

    console.log(arrList.indexOf('12'))
    >> 0
    console.log(arrList.indexOf('d'))
    >> 4
    console.log(arrList.indexOf('sdfds'))
    >> -1
</script>
View Code

利用indexOf()方法:获取元素在数组中的索引

假如存在返回索引

  不存在返回:-1

所以:if(arrList.indexOf(element)>=0){

      console.log('存在!');  

    }

猜你喜欢

转载自www.cnblogs.com/yanxiatingyu/p/9451533.html
今日推荐