在Javascript中使用indexOf比较变量类型编号和数组

Bru*_*lva 5 javascript arrays 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";
      }

   }
}
Run Code Online (Sandbox Code Playgroud)

nem*_*035 4

语句if会将传递给它的任何内容评估为布尔值。

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

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

if (array.indexOf(element))
Run Code Online (Sandbox Code Playgroud)

将始终评估为 true。

if (array.indexOf(element))
Run Code Online (Sandbox Code Playgroud)

您可以使用直接比较-1

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

或者更新的、更干净的Array.prototype.includes

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