2011-12-20 197 views
5

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

回答

10

Math.random會給你一個0(含)和1(不含)之間的浮點數。

乘以256會給你一個範圍爲0(含)至256(不含)的數字,但仍然是浮點數。

參加該號碼的發言將給你一個整數 0和255之間(包括兩端)。

這是從0到255的整數,您需要構造像rgb(72,25,183)這樣的RGB值。

1

Math.floor將給出一個整數並去除小數。

Math.random返回一個介於0和1之間的數字,因此當乘以256時會產生十進制數。這就是爲什麼要使用floor去除小數,否則rgb值將不起作用。

1

Math.floor()是刪除Number的小數部分。這與Math.ceil()相反。

您也可以將反向位運算符(~~)加倍以實現與Math.floor()相同的效果(儘管floor()方法當然對大多數人來說可讀性更高)。

~~(Math.random() * 256) 
2

這似乎是一個隨機顏色期望 - 一個與各個組成隨機0和255之間

Math.random()上返回的隨機數[0,1)(即,它可以是確切地0或至多但不包括一個)。

將該隨機值乘以256得到範圍[0,256)上的隨機數(即它可以是255.99,但從不是256)。幾乎在那裏,但不完全。

Math.floor()將數字向下舍入爲最接近的整數,根據需要在[0,255]上產生一個整數。

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)