Math.floor math.random (+ min 在做什么)

Math.floor math.random (what is the + min doing)

本文关键字:什么 min floor math random Math      更新时间:2023-09-26
var min = 1; 
var max = 50;
var array = []; 
var randomNumber = Math.floor(Math.random() * (max - min) + min); 
for (var i=0; i<randomNumber; i++) {
    array.push(Math.floor(Math.random() * (max - min) + min));
}
console.log(array);

为此,我们可以解释 + min 在做什么吗?如果我们去掉 + min,只做 Math.floor(Math.random(( * (max - min((,会有什么区别?

添加min会将表达式中可以获取的值范围从 [0, max - min] 移动到 [min, max]。

我们知道

Math.floor(Math.round()*6);返回一个范围 [0,6( 或 0,1,2,3,4,5 范围内的值。在这里,我们得到了 6 个数字。

假设我们要生成从 5 到 10(包括 5 和 10(的数字。我们需要知道有多少个数字。 var min = 5; var max = 10; 如果我们将它们列出,5、6、7、8、9、10 并计算它们,我们看到总共有 6 个数字。我们从之前知道,我们将不得不乘以 6 才能得到 6 个数字。

如果你这样做max - min你会得到 5,也就是 1 个短。 max - min为您提供从 5 到 10 的距离。如果你想要数字的总数,你总是必须加1。

这给了我们表达式max - min + 1并将其放入公式中:

Math.floor(Math.random() * (max - min + 1));

此时,公式可以生成正确数量的数字,但它们始终从 0 开始,因为 Math.random 的范围从 0 开始。

0, 1, 2, 3, 4,  5 // What we have
5, 6, 7, 8, 9, 10 // What we want

请注意,如果我们在第一行中的所有数字上加 5,我们将得到第二行。 5 是我们在示例中的最小值。

因此,如果我们将最小值添加到公式的末尾,它将把所有数字转移到我们想要的数字上。

Math.floor(Math.random() * (max - min + 1)) + min;