Javascript:我把Math.floor(Math.random)放在哪里?



好吧,我显然是个十足的新手,所以请温柔一点。在学习Javascript的过程中,我创建了一个测试来更好地帮助我记住和练习这些信息。下面是到目前为止我的代码示例(实际的数组已经被缩短了)。

在我的学习进度中,我的工作很好,除了我似乎不能使用Math.floor(Math.random())来创建一个非线性q &经验。

var qAndA = [["What starts a variable?", "var"], 
["What creates a popup with text and an OK button?", "alert()"],  
["What is the sign for a modulo?", "%"]];
function askQuestion(qAndA) {
    var answer = prompt(qAndA[0], " ");    
    if (answer === qAndA[1]) { 
        alert("yes");
    } else {
        alert("No, the answer is " + qAndA[1]);
    }
}
for (i = 0; i < qAndA.length; i++) {
    askQuestion(qAndA[i]);
} 

我已经看了这里和其他地方所有可能的答案,但没有一个能解决这个问题。

有谁能帮帮我吗?

在数组中选择随机元素的最简单方法:

var randomIndex = Math.floor(Math.random() * qAndA.length)
var randomQuestion = qAndA[randomIndex]

现在放入循环:

var questionsToAsk = qAndA.length
for (i = 0; i < questionsToAsk; i++) {
    var randomIndex = Math.floor(Math.random() * qAndA.length)
    var randomQuestion = qAndA[randomIndex]
    askQuestion(randomQuestion);
} 

使用

中的| 0更快
const randomIndex = Math.random() * qAndA.length | 0;
const randomQuestion = qAndA[randomIndex];

| 0是二进制 0, JavaScript规范有效地说结果在|发生之前转换为整数。注意,| 0Math.floor不同。| 0四舍五入为0,Math.floor四舍五入为0。

         | 0   Math.floor         
------+------+------------
  2.5 |   2  |   2
  1.5 |   1  |   1
  0.5 |   0  |   0
 -0.5 |   0  |  -1
 -1.5 |  =1  |  -2
 -2.5 |  -2  |  -3

最新更新