需要解释一下这个javascript吗

需要解释一下这个javascript吗,javascript,math,Javascript,Math,我对我找到并使用的这个脚本有一个问题。这很有效,但我不明白为什么。这个练习是列出一个从-50到50的随机数。下面的函数使用Math.floorMath.random*我不理解的部分 如果我把这个计算放在谷歌上,我得到的答案是151和数学 有人能给我一个关于这个函数的明确解释吗,因为我确信我遗漏了一些东西 这个脚本可以工作,但我只想清楚地解释一下如何工作 这正是我们所要求的 random返回数组中的浮点伪随机数 范围[0,1,即从0(包括0)到但不包括1 独家,然后您可以缩放到所需的范围 当它与一

我对我找到并使用的这个脚本有一个问题。这很有效,但我不明白为什么。这个练习是列出一个从-50到50的随机数。下面的函数使用Math.floorMath.random*我不理解的部分

如果我把这个计算放在谷歌上,我得到的答案是151和数学

有人能给我一个关于这个函数的明确解释吗,因为我确信我遗漏了一些东西

这个脚本可以工作,但我只想清楚地解释一下如何工作

这正是我们所要求的

random返回数组中的浮点伪随机数 范围[0,1,即从0(包括0)到但不包括1 独家,然后您可以缩放到所需的范围

当它与一个大于1的数字相乘并加上floored时,会得到一个整数

Math.random-仅获取介于0和1之间的值。 Math.floor number从数字中获取整数向下舍入值。 你应该:

function randomFromTo(from, to)
{
  // you can use doubled bitwise NOT operator which also as Math.floor get integer value from number but is much faster.
  // ~1 == -2 , ~-2 == 1 and   ~1.5 == -2 :)

 return  ~~( --from + ( Math.random() * ( ++to - from )) )
}

谢谢!这是我要问的快速问题:Math.random是否返回1.0?如果是,这是否意味着51可以从OP的randomFromTo函数返回?不,它不包含。它从不包含1.0。谢谢bobbymcr纠正我糟糕的英语。
to - from + 1 = 50 - (-50) + 1 = 101
Math.random() * 101 = number in range [0,101[
Math.floor([0,101[) = integer in range [0,100]
[0,100] + from = [0,100] + (-50) = integer in range [-50,50]
function randomFromTo(from, to)
{
  // you can use doubled bitwise NOT operator which also as Math.floor get integer value from number but is much faster.
  // ~1 == -2 , ~-2 == 1 and   ~1.5 == -2 :)

 return  ~~( --from + ( Math.random() * ( ++to - from )) )
}