繁体   English   中英

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

[英]Explain Math.floor(Math.random())

我见过许多使用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值,如rgb(72,25,183)

它似乎是一种随机颜色 - 每个组件随机在0到255之间。

Math.random()在[0,1]上返回一个随机数(即它可能正好为零或高达但不包括一个)。

将该随机值乘以256得到范围[0,256]上的随机数(即它可以是255.99,但绝不是256)。 几乎在那里,但并不完全。

Math.floor()将数字向下Math.floor()入到最接近的整数,使结果根据需要在[0,255]上为整数。

Math.floor将给出一个整数并删除小数。

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

Math.floor()将删除Number的小数部分。 它与Math.ceil()相反。

您也可以将反转按位运算符( ~~ )加倍,以实现与Math.floor()相同(当然, floor()方法对大多数人来说更具可读性)。

~~(Math.random() * 256)

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM