Explain Math.floor(Math.random())

前端 未结 6 1183
轻奢々
轻奢々 2020-12-19 07:52

I have seen many places using Math.floor() and Math.random()

like below

$(\'a.random-color\').hover(function() { //mouseove         


        
6条回答
  •  时光取名叫无心
    2020-12-19 08:07

    It seems a random color is desired - one with each component random between 0 and 255.

    Math.random() returns a random number on [0,1) (ie it may be exactly zero or up to but not including one).

    Multiplying that random value by 256 gives a random number on the range [0,256) (ie it may be 255.99, but never 256). Almost there, but not quite.

    Math.floor() rounds the number downwards to the nearest whole integer, making the result an integer on [0,255] as desired.

提交回复
热议问题