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?
Other solutions:
(Math.random() * 6 | 0) + 1
~~(Math.random() * 6) + 1
In order to create a random number in javascript we can use the built in javascript
Math
object. TheMath
object holds a functionMath.random()
. This function does the following (source MDN):Given this functionality we can easily scale this into more complex scenarios. For example:
Math.random()
From the Mozilla Developer Network documentation:
Useful examples:
Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.
CODE:
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.