Wednesday 26 April 2017

Generate random number between two numbers in JavaScript



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?


Answer



Important



The following code works only if the minimum value is 1. It does not work for minimum values other than 1.




If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:



Math.floor(Math.random() * 6) + 1  


Where:




  • 1 is the start number

  • 6 is the number of possible results (1 + start (6) - end (1))



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...