Explain Math.floor(Math.random())

8
我曾经看到许多地方使用Math.floor()Math.random(),就像下面这样。
$('a.random-color').hover(function() { //mouseover
    var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $(this).animate({
      'color': col,
      'paddingLeft': '20px'
    },1000);
  },function() { //mouseout
    $(this).animate({
      'color': original,
      'paddingLeft': '0'
    },500);
  });
});

为什么要使用 Math.floor()Math.random() 呢?

6个回答

12

Math.random会给你一个介于0(包括)和1(不包括)之间的浮点数。

将其乘以256将会得到范围在0(包括)到256(不包括)之间的浮点数。

取该数的整数部分,将会得到一个介于0到255(都包括)之间的整数。

正是这个0到255之间的整数,你需要构造RGB值,例如rgb(72,25,183)


3

看起来需要一个随机颜色 - 每个部分的值都在0到255之间。

Math.random()返回一个[0,1)范围内的随机数(即它可能恰好为零,或者小于但不包括一)。

将该随机值乘以256会得到一个[0,256)范围内的随机数(即它可能是255.99,但永远不会是256)。接近成功,但还不够。

Math.floor()将数字向下舍入到最近的整数,使结果成为所需的[0,255]范围内的整数。


1

Math.floor会给出一个整数并且去掉小数。

Math.random返回0到1之间的数字,而当乘以256时会产生小数。这就是为什么你想使用floor来除去小数,否则rgb值将无法运作。


1

Math.floor() 是用来去除 Number 的小数部分。它是 Math.ceil() 的相反操作。

你也可以使用双重按位取反运算符 (~~) 来实现与 Math.floor() 相同的效果(当然,对于大多数人来说,floor() 方法更易读)。

~~(Math.random() * 256)

1

Math.random返回0到1之间的值。您将其乘以256,因此它将返回0到256之间的某个浮点值。math.floor将从中省略小数部分。


0

~~Number 只是正数的 Math.floor()。对于负数,它是 Math.ceil()

对于正数,您可以使用:

Math.floor(x) == ~~(x)

Math.round(x) == ~~(x + 0.5)

Math.ceil(x) == ~~(x + 1)

对于负数,您可以使用:

Math.ceil(x) == ~~(x)

Math.round(x) == ~~(x - 0.5)

Math.floor(x) == ~~(x - 1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接