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

查看:137
本文介绍了解释Math.floor(Math.random())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多地方使用 Math.floor() Math.random()

I have seen many places using Math.floor() and 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(独占)之间的浮点数。

Math.random will give you a floating point number between 0 (inclusive) and 1 (exclusive).

乘以256会给你0(包括)到256(不包括)范围内的数字,但仍然是浮点数。

Multiplying that by 256 will give you a number in the range 0 (inclusive) through 256 (exclusive), but still floating point.

取这个数字的最后一个将给你一个整数介于0和255之间(包括两者)。

Taking the floor of that number will give you an integer between 0 and 255 (both inclusive).

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

It's the integer from 0 to 255 that you need to construct RGB values like rgb(72,25,183).

这篇关于解释Math.floor(Math.random())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆