繁体   English   中英

如何在js中查找数组是否有随机数[Math.floor((Math.random() * 10) + 1)]

[英]How to find if an array has a random number [Math.floor((Math.random() * 10) + 1)] or not in it in js

我正在尝试用 html、css、js 创建一个刽子手游戏。 所以我现在要根据问题的显示方式对其进行随机化-

创建随机数 - Math.floor((Math.random() * 10) + 1)

首先检查数组(这个数组包含哪些问题已经完成)是否有随机数

如果不 如果是
然后允许下面的语句发生 然后让函数再次运行,直到随机数不在数组中

基于随机数的第一个问题和第二个olso等等

但实际上我无法弄清楚如何检查具有随机数的数组。 我试过了:-

这有效

function NextQuestion() {
  let done = ['1','2'];
  let random = Math.floor((Math.random() * 10) + 1);
  let include = done.includes('1');  
  if (include == true) {
    alert('true');// this works
  }
}

这不

function NextQuestion() {
  let done = ['1','2'];
  let random = Math.floor((Math.random() * 10) + 1);
  let include = done.includes(random);  
  if (include == true) {
    alert('true');// this does not works
  }
}

不同之处在于,在第一个中它包含 includes('1'); 但在第二个它包含(随机);

如果您知道为什么会发生这种情况,请告诉我,并提供解决此问题的方法

提前致谢。

这将解释为什么

 let random = Math.floor((Math.random() * 10) + 1); console.log(random) console.log( ["1","2","3","4","5","6","7","8","9","10"].includes(random) ); console.log( [1,2,3,4,5,6,7,8,9,10].includes(random) );

因此,如果您在创建随机数时存储随机数,您的刽子手将起作用

@mplungian 正确回答了您在标题中提出的问题。 但是我相信如果想以随机顺序询问给定数量的问题,您就走错了路。 为此,您应该简单地使用 for 循环遍历问题数组。 但在你这样做之前,应该对数组进行洗牌:

 function shfl(a){ // Durstenfeld shuffle: for(let i=a.length;i>1;){ j=Math.floor(Math.random()*i--); if (i!=j) [a[i],a[j]]=[a[j],a[i]] } return a } const q=[1,2,3,4,5,6,7,8,9,10]; shfl(q); q.forEach((n,i)=>console.log(i+1+". Q"+n));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM