开发者

How to generate random number with js from range starting from 1?

开发者 https://www.devze.com 2023-03-06 03:56 出处:网络
I\'ve been using this code to generate a random number with js: var max = 10; Math.floor( Math.random() * ( max + 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:

  1. Subtract x from max
  2. Do everything else as normal
  3. Add x to the result


You do from 0 to 9, then you add one to the result.

0

精彩评论

暂无评论...
验证码 换一张
取 消