Explain Math.floor (Math.random ())

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

as below

$('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);
  });
});

Why use Math.floor()and Math.random()?

+5
source share
6 answers

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

Multiplying this by 256, you get a number in the range from 0 (inclusive) to 256 (exceptional), but still a floating point.

Taking the word of this number, you get an integer from 0 to 255 (both inclusive).

This is an integer from 0 to 255, which you need to create RGB values ​​such as rgb(72,25,183).

+10
source

, - 0 255.

Math.random() [0,1) (.. , ).

256, [0,256) (.. 255.99, 256). , .

Math.floor() , [0,255] .

+2

Math.floor .

Math.random 0 1 256. , , rgb .

+1

Math.floor() - Number. Math.ceil().

(~~), , Math.floor() (, , floor() ).

~~(Math.random() * 256)
+1

Math.random 0 1. 256, 0 256. math.floor .

+1

~~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)
0

All Articles