【问题标题】:How to find if an array has a random number [Math.floor((Math.random() * 10) + 1)] or not in it in js如何在js中查找数组是否有随机数[Math.floor((Math.random() * 10) + 1)]
【发布时间】:2021-07-29 11:37:15
【问题描述】:

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

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

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

if not if yes
then allow the below statement to happen then let the function run again and agiin until random number is not there in th array

第一个问题基于随机数和第二个 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'); 但第二个有 includes(random);

你知道为什么会发生这种情况吗?如果你知道,请告诉我,并请给出解决这个问题的方法

提前致谢。

【问题讨论】:

  • 随机是一个数字,你的数组包含字符串。

标签: javascript html css arrays


【解决方案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)
);  

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

【讨论】:

【解决方案2】:

@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));

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 1970-01-01
    • 2022-11-23
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多