Test for value in Javascript Array

This question already has an answer here:

  • Shorten JS if or statement [duplicate] 5 answers
  • How do I check if an array includes an object in JavaScript? 40 answers

  • 使用indexOf来查看x是否在数组中。

    if([1,2].indexOf(x) !== -1)
    

    尝试使用数组,然后使用.indexOf()

     var myNumbers = [1,2];
     var foo = 4;
     var bar = 1;
    
     var exists = (myNumbers.indexOf(bar) > -1); //true
     var notExists = (myNumbers.indexOf(foo) > -1); //false
    

    使用Array .includes方法。

    if ([1, 2].includes(x)) {
      // array has x
    }
    
    链接地址: http://www.djcxy.com/p/13036.html

    上一篇: 检查数组中是否存在值(AngularJS)

    下一篇: 测试Javascript数组中的值