Javascript 解释Math.floor(Math.random())

Javascript 解释Math.floor(Math.random()),javascript,jquery,Javascript,Jquery,我见过很多地方使用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).

我见过很多地方使用
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()

Math.random
将为您提供一个介于0(包括)和1(不包括)之间的浮点数

将该值乘以256将得到一个介于0(包括)到256(不包括)之间的数字,但仍然是浮点数

以该数字为底将得到一个介于0和255(包括0和255)之间的整数


要构造RGB值,需要0到255之间的整数,如
RGB(72,25183)
Math.floor将给出一个整数并去掉小数

Math.random返回一个介于0和1之间的数字,因此与256相乘时将产生十进制数。这就是为什么要使用floor来去除小数,否则rgb值将不起作用。

数学.floor()是删除
数字的小数部分。它与
Math.ceil()
相反

您还可以将逆位运算符(
~
)加倍,以实现与
Math.floor()
相同的效果(当然
floor()
方法对大多数人来说可读性更高)


似乎需要一种随机颜色-每个组件的随机颜色介于0和255之间

返回[0,1]上的一个随机数(即它可能正好为零或最多为一,但不包括一)

将该随机值乘以256得到一个范围为[0256]的随机数(即它可能是255.99,但永远不会是256)。几乎在那里,但不完全在那里


将数字向下舍入到最接近的整数,使结果成为[0255]上的整数根据需要。

Math.random返回0到1之间的值。您将其与256相乘,因此它将返回0到256之间的一些浮点值。Math.floor将忽略其中的分数值。

~~ 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)
对于负数,您可以使用:

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)