How to generate random numbers in JavaScript – Math.random

June 28, 2020



JavaScript makes it really easy to generate and use pseudo-random numbers. By using the built-in Math.random() function, you are able to achieve just that.

Math.random() will give you a random floating point number from 0 to 1 (non-inclusive of 1) and so to convert that result into a whole number, you’ll need to implement some basic math.

In this video I show you a simple example of how to generate a random number and also how to generate a random whole number (or integer) between a range of 1 and X.

For your reference, check this out:

Support me on Patreon:

Follow me on Twitter @dcode!

If this video helped you out and you’d like to see more, make sure to leave a like and subscribe to dcode!

#dcode #javascript #webdev

Nguồn: https://mensagensdamanha.com/

Xem thêm bài viết khác: https://mensagensdamanha.com/cong-nghe/

All Comments

  • Perfect – thanks!

    Matt Price June 28, 2020 10:56 pm Reply
  • Good tutorial, thanks

    Tim D June 28, 2020 10:56 pm Reply
  • Thanks man, you saved my life with this! I want to create a game where you have 50% chance of death, and it really helped. thanks man!!!!!!

    Aron Szasz June 28, 2020 10:56 pm Reply
  • Why the * 1 at the end ?

    Christopher Webb June 28, 2020 10:56 pm Reply
  • whats the use of +1 ????

    Nikos Spiropoulos June 28, 2020 10:56 pm Reply
  • Well explained. Thank you.

    Be Maat June 28, 2020 10:56 pm Reply
  • 👍👍

    CODE4WIN June 28, 2020 10:56 pm Reply
  • Hi Dom, I have a question on this while I was looking through it. I don't know why it's more common to see Math.floor() more than Math.round(). Why is that? Does anyone know?

    hyfyooie June 28, 2020 10:56 pm Reply
  • For people who want to do random numbers between two numbers that are not 1 to whatever, here is an example:
    var minAge = 14 ;

    var maxAge = 36-minAge ;

    var Age = Math.floor(Math.random() * maxAge ) + minAge +1;

    Ran Müller June 28, 2020 10:56 pm Reply
  • seems like this could be useful for creating a hash function, is that a thing?

    Diastrus June 28, 2020 10:56 pm Reply
  • How can I do a random of one list of numbers? For example 3 3 3 5 6 7 0 0 0 0 and no repeat please

    Maestro maestros June 28, 2020 10:56 pm Reply
  • Like your intro..wow

    Yashwanth June 28, 2020 10:56 pm Reply

Leave a Reply

Your email address will not be published. Required fields are marked *