简体   繁体   中英

Javascript/html: How to generate random number between number A and number B?

We have a form with 2 fields and a button. We want on button click to output random int number (like 3, 5 or 33) which would lie between int A and int B? (no use of jQuery or anything like it is required)

You can use Javascript Math.random

function randomInRange(start,end){
       return Math.floor(Math.random() * (end - start + 1) + start);
}

使用类似Math.floor(Math.random()*(intB-intA +1)) + intA

Like this:

Math.floor(a + Math.random() * (b - a))

The Math.random() method returns a random floating-point number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM