【问题标题】:How to check value in the array is present in the array variable or not? [duplicate]如何检查数组中的值是否存在于数组变量中? [复制]
【发布时间】:2019-12-27 17:24:48
【问题描述】:

我想实现数组中的某个值是否存在于数组变量中。

var a = [1, 2, 3];
if (a === 1) {
    alert("green");
}

所以我的目标是检查变量 a 是否保持值 1。

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您需要遍历数组成员并检查是否有任何成员具有该值。这是一个例子:

    var a = [1,2,3];
    for(let i = 0; i < a.length; i++){
       if(a[i] == 1){
          alert("green");
       }
    }
    

    【讨论】:

      【解决方案2】:

      使用includes:

      let a = [1, 2, 3]
      
      if (a.includes(1))
        console.log('exist');
      else
        console.log('not exist');

      【讨论】:

      • 这就是我想要的。谢谢暗里
      • @SagarSinha 虽然这是一个重复的问题,但如果这是正确的答案,你应该标记它。祝你好运!
      • 我已经投票并接受了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2019-10-16
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多