How can I generate a random whole number between two specified variables in Javascript, e.g. x = 4
and y = 8
would output any of 4, 5, 6, 7, 8?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Do the Java Integer and Double objects have unnece
- Keeping track of variable instances
This can handle generating upto 20 digit UNIQUE random number
JS
JsFiddle
Alternate Solution :-
I know this question is already answered but my answer could help someone.
I found this simple method on W3Schools:
Hope this would help someone.
I got wondering how the distribution after enough runs would be for such a randomizer function.
And also to check if that distribution would be more-or-less the same in the different browsers.
So here's a snippet to run. The numbers can be changed before pressing the button.
Random whole number between lowest and highest:
Not the most elegant solution.. but something quick.
Here's what I use to generate random numbers.
We do execute
high++
becauseMath.random()
generates a random number between 0, (inclusive), and 1(exclusive) The one being excluded, means we must increase the high by one before executing any math. We then subtract low from high, giving us the highest number to generate - low, then +low, bringing high back to normal, and making the lowest number atleast low. then we return the resulting numberrandom(7,3)
could return3,4,5,6, or 7