Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
If you wanted to get between 1 and 6, you would calculate:
Where:
Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.
E.g
Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.
I wrote more flexible function which can give you random number but not only integer.
Fixed version.
Example
Return a random number between 1 and 10:
The result could be:
3
Try yourself: here
--
or using lodash / undescore:
_.random(min, max)
Docs: - lodash - undescore
I found Francisc's solution above did not include the min or max number in the results, so I altered it like this:
jsfiddle: https://jsfiddle.net/cyGwf/477/
Random Integer: to get a random integer between
min
andmax
, use the following codeRandom Floating Point Number: to get a random floating point number between
min
andmax
, use the following codeReference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random