How to generate random number with js from range starting from 1?
I've been using this code to generate a random number with js:
var max = 10;
Math.floor( Math.random() * ( max + 1 ) );
From what I understand that will generate a number from 0 to 10, but what if I want to generate a开发者_运维问答 random number from 1 to 10? or from 5 to 10?
try this:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
If you want to start from x
instead of 0, then:
- Subtract
x
frommax
- Do everything else as normal
- Add
x
to the result
You do from 0 to 9, then you add one to the result.
精彩评论