Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shortest Code For Random Number Between 1 And N In Javascript
#1
Here I want to show you a tip for creating a random number between 1 and N in easiest and shortest way.
Code


Here is the code:

~~(Math.random () * N ) + 1

Code in textarea:


All you need to do is to replace N with your upper number.

How?
In JavaScript we have Math.random () which creates a random number between 0 and 1, e.g. 0.3577353348955512.

We use this function to have a random number, then we multiply that to our upper number (e.g. 6):

0.3577353348955512 * 6 =
2.1464120093733072

And then we get the floor number with double ~ operator
It takes so long to learn simplicity.
#2
make The Code In Textarea Sir pls
I am a proud member of NIgerian Coders Team
Reply
#3
(01-03-2017, 10:01 AM)naijaboy Wrote:
make The Code In Textarea Sir pls

Done!

***The code is just a one line code, dont know why you still need it in textarea***
I am a proud member of NIgerian Coders Team
Reply
Facebook Share


Possibly Related Threads...
Thread
  HELP: How Can I Create A Javascript Ads Rotator For My Site
  Beginner Javascript Coding Mistakes To Avoid
  Please Help With This Code
  I Need Help With This JQuery Code
  Concatenate Many Arrays Uniquely With Javascript
  Javascript Time Ago Function
  Javascript Text Editor Right In Your Browser In One Line Of Code
  Getting Current Location With Javascript
  How To Check If Javascript Object Is Empty
  How To Create An Image Slider With Javascript




Users browsing this thread: 1 Guest(s)