在Javascript中使用indexOf将变量类型编号与数组进行比较

在Javascript中使用indexOf将变量类型编号与数组进行比较,javascript,arrays,indexof,Javascript,Arrays,Indexof,我在按钮中添加了一个单击事件侦听器。它调用按钮YES和NO。基本上,indexOf检查变量foto中的值是否在yessetup数组或notMeetup数组中 我试图调试,但我总是得到“You got it”,当我单击NO按钮时,它不会调用调试器 let foto = Math.floor(Math.random() * 20) + 1; document.querySelector('.btn').addEventListener('click', verify); function ver

我在按钮中添加了一个
单击
事件侦听器。它调用按钮
YES
NO
。基本上,
indexOf
检查变量
foto
中的值是否在
yessetup
数组或
notMeetup
数组中

我试图调试,但我总是得到“You got it”,当我单击
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";
      }

   }
}

if
语句将计算作为布尔值传入的任何内容

它不会执行“true”分支的唯一值都是假值:
0
null
未定义的
'
false
NaN

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

if (array.indexOf(element))
将始终评估为真实

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

}
您可以将单击事件添加到按钮并检查随机变量的值。按照您编写代码的方式,它将始终返回两种场景的值。或者,要在运行时检查值,可以使用alert()

您正在单击函数外生成随机数。在这种情况下,该数字在运行时被设置为stone,并且永远不会再次更新。如果希望在每次触发单击事件时生成新的随机数,则需要在
verify()
方法中指定
foto
变量。此外,假设元素存在,
yesButton
noButton
都将返回true。您需要检查事件目标以确定单击了哪个按钮。Like
e.target.id==“yes”
yes按钮
返回一个元素。如果它存在于DOM上,它将始终是一个
truthy
值。它可能应该是
yesButton.value
实际上这个变量foto需要进入这个函数gerar(),但好像我把它放进去了,它就在这个函数的作用域上,我决定把它放在函数gerar()之外{var score=document.getElementById('score'));var fotoDOM=document.querySelector('.foto');fotoDOM.src='foto-'+foto+'.jpg';console.log(foto);document.getElementById('photo')。style.animation=“appeaperson 1s”;score.innerHTML=foto;foto;}但是我必须得到这个foto变量并与verify()中的数组进行比较,但是这个foto变量需要留在函数verify中。如何在不更改gerar()内部生成的数字的情况下,将此变量foto放入函数verify中??