首页 > 解决方案 > 在Javascript中使用indexOf将变量类型号与数组进行比较

问题描述

我已将click事件侦听器添加到按钮。它调用按钮YESAND NO。基本上indexOf检查变量中的值foto是在yesMeetup数组中还是在notMeetup数组中。

我试图调试,但我总是得到“你知道了”,当我点击NO按钮时它没有调用调试器

let foto = Math.floor(Math.random() * 20) + 1;

document.querySelector('.btn').addEventListener('click', verify);

function verify() {
   var yesMeetup = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15];
   var notMeetup = [16, 17, 18, 19, 20];
   var notButton = document.getElementById('no');
   var yesButton = document.getElementById('yes');
   var decisao = document.getElementById('decisao');
   debugger;

   if (yesButton) {

        if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "You got it";
      } else if (notMeetup.indexOf(foto)) {
         decisao.textContent = "wrong";
      }

   } else if (notButton) {

      if (notMeetup.indexOf(foto)) {
         decisao.textContent = "You Gou it";
      } else if (yesMeetup.indexOf(foto)) {
         decisao.textContent = "Wrong";
      }

   }
}

标签: javascriptarraysindexof

解决方案


语句将评估传递给它的if任何东西作为布尔值。

它不会执行“真”分支的唯一值都是假值:0, null, undefined, '', false, NaN

Array.prototype.indexOf-1当数组中不存在元素时返回,这不是虚假值之一,因此您的if条件

if (array.indexOf(element))

将始终评估为真。

var example = [1,2,3];
if (example.indexOf(4)) {
  console.log('still true');
}

您可以使用直接比较-1

var example = [1,2,3];
if (example.indexOf(4) !== -1) {
  console.log('this is not logged');
}

或者更新的,更清洁的,Array.prototype.includes

var example = [1,2,3];
if (example.includes(4)) {
  console.log('this is not logged');
}


推荐阅读