Best Website-BuildersBest Website-Builders
    What's Hot

    8 Best Tents (2023): Backpacking, Family, and Ultralight

    March 21, 2023

    Cost of living: How can I save money on my food shop?

    March 21, 2023

    Man charged over abusive email to Angela Rayner

    March 21, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      A great SSG just got better

      March 21, 2023

      Why Developers Can’t Go Back After Using Tailwind CSS

      March 21, 2023

      Dubai-based CSS founder wins title of best website design site in India

      March 21, 2023

      CSS exam essay

      March 21, 2023

      Add space to left of background image – HTML & CSS – SitePoint Forums

      March 20, 2023
    • Joomla

      Reseller Hosting Business: Important Q&A

      March 21, 2023

      Web Hosting: 8 Elements Every Entrepreneur Should Look For

      March 20, 2023

      VS Code Extension for In-Browser Development, WapuuGotchi Gamification Plugin & More – WP Tavern

      March 20, 2023

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023
    • PHP

      How Chris Ute found his best friend in Penn Badgley

      March 21, 2023

      March 21, 2023 — Biggest news story of the day

      March 21, 2023

      5 murder trials where jurors visited crime scenes

      March 21, 2023

      Emma Chamberlain shuts down online shop after charging DMs $10,000

      March 20, 2023

      Aurora man arrested for allegedly poisoning wife with smoothie

      March 20, 2023
    • UX

      Baidu deploys AI-powered chatbot ‘Ernie Bot’ to improve user experience

      March 21, 2023

      Rapid Finance announces availability of Decisioneer, an integrated digital business lending platform

      March 21, 2023

      Proximus Expands Partnership with ThinkAnalytics to Enhance New Pickx UX

      March 21, 2023

      UI and UX Design Software Market by 2023 (New Research)

      March 21, 2023

      The UI and UX Design Software Market 2023 (New Research) Report reveals key insights into the growth opportunities and trends shaping the future of this industry.

      March 21, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Google Bard has been released. Here are my first impressions of ChatGPT’s competitors:

      March 21, 2023

      Nvidia’s RTX 4000 SFF Solves My Biggest GPU Problem – But There’s a Pitfall

      March 21, 2023

      Everwild: Everything we know so far

      March 21, 2023

      Most companies are unprepared to respond to major security incidents.

      March 21, 2023

      The Pixel Watch finally got this life-saving Apple Watch feature.tech radar

      March 21, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » Generate Random Numbers with Math.random() in JavaScript — SitePoint
    JavaScript

    Generate Random Numbers with Math.random() in JavaScript — SitePoint

    websitebuildersnowBy websitebuildersnowSeptember 20, 2022No Comments10 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In this article, we’ll look at how to generate random numbers in JavaScript. Math.random()load random images, select random elements from arrays, generate random colors, characters, strings, phrases, and passwords, and build reusable functions for a wide range of purposes.

    Randomness in JavaScript

    It’s always nice to be able to add an element of randomness to your program. You may want to spice up your website by adding random styles, generating random phrases, or adding an element of chance to your game (for example, in this Numble game these are widely used).

    Unfortunately, creating truly random values ​​is actually very difficult (unless you have access to radioactive material or use a monkey with a keyboard). To avoid this, programming languages ​​generate using deterministic methods. pseudorandom number.these are numbers appear Random, but actually generated by a function that accepts seed value Based on events such as mouse pointer time and position.

    in JavaScript random Functions that are built-in methods Math object. The ECMAScript standard does not specify how this function generates random numbers, so implementation is left to browser vendors. At the time of this writing, all major browsers use his xorshift128+ algorithm in the background to generate pseudo-random numbers.

    To use, simply enter Math.random() and returns a pseudorandom floating point decimal number between 0 (inclusive) and 1 (exclusive).

    const x = Math.random();
    

    This can be expressed as the following inequality:

    0 <= x < 1
    

    But what if you want a random number greater than 1? Easy: Just multiply and zoom in. For example, multiplying the result by 10 produces a value between 0 (inclusive) and 10 (exclusive).

    const y = Math.random()*10
    

    The reason for this can be seen by multiplying both sides of the previous inequality by 10.

    0 <= y < 10
    

    However, the result is still a floating point decimal number. What if we want a random integer? Simple: all we need to do is Math.floor Use a function to round the return value to an integer below. The following code assigns a random integer between 0 and 9 to a variable. z:

    const z = Math.floor(Math.random()*10)
    

    Note that multiplying by 10 only returns values ​​up to 9.

    You can generalize this method to create a function that returns a random integer between 0 and up to 0. but does not includea number provided as an argument:

    function randomInt(number){
      return Math.floor(Math.random()*(number))
    }  
    

    You can use this function to return a random number between 0 and 9.

    const randomDigit= randomInt(10)
    

    Now you have a way to create random integers. But what about random integers between two different values ​​that don’t necessarily start at zero? Using the code above, addition Value to start the range with. For example, if you want to generate a random integer between 6 and 10, use the code above to generate a random integer between 0 and 4 and add 6 to the result.

    const betweenSixAnd10 = Math.floor(Math.random()*5) + 6
    

    to generate a random integer between 0 and 4actually had to hang 5.

    You can generalize this method to create a function that returns a random integer between two values.

    function randomIntBetween(min,max){
      Math.floor(Math.random()*(max - min + 1)) + min
    }   
    

    This is a simple generalization of the code I wrote to get a random number between 6 and 10, but with 6 as min parameter and 10 is max parameter. To use it, simply enter two arguments representing the upper and lower bounds of the random number (inclusive). So to simulate rolling a hexahedral die, you can use the following code to return an integer between 1 and 6.

    const dice = randomIntBetween(1,6)
    

    How randomIntBetween the function works. In the demo below I am connecting to some HTML so you can change the values. min and max Click the button to generate a random integer (this can be used to replicate the various size dice used in Dungeons & Dragons and similar games).

    look at the pen
    Random Integer – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    There are some functions for generating random integers, so you can do interesting things with them.

    Load random image

    first, randomInt Ability to load random photos from the Lorem Picsum website. This site provides a database of placeholder images, each with a unique integer ID. This means that you can create links to random images by inserting random integers into the URL.

    Simply set the following HTML to display an image with an ID of 0.

    <button id="randomPhoto">Random Photo</button>
    <p id="photo"><img src="https://picsum.photos/id/0/200/200"></p>
    

    Then hook the following JavaScript to generate a random integer for the ID and update the HTML to randomly display a new image when the button is clicked.

    document.getElementById("randomPhoto").addEventListener("click",e => document.getElementById("photo").innerHTML = `<img src="https://picsum.photos/id/${randomInt(100)}/200/200">`)
    

    You can see this in the CodePen demo below.

    look at the pen
    Random Photo – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random colors

    In HTML and CSS, colors are represented by three integers from 0 to 255, written in hexadecimal (base 16). The first represents red, the second represents green, and the third represents blue.This means that we can use randomInt Use a function to generate three random numbers between 0 and 255 and convert them to base 16 to create random colors.To convert a number to another base, replace the argument with toString method, the following code returns a random hexadecimal number between 0 and FF (255 hex).

    randomInt(0,255).toString(16)
    << 2B
    

    with this, randomColor Functions that return HTML color codes:

    function randomColor(){ 
      return `#${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}`
    }
    

    This returns a template literal that starts with a hash character that starts with every HTML color code, and concatenates three random integers between 0 and 255 in hexadecimal at the end.

    call randomColor The function returns a random HTML color string.

    randomColor()
    << #c2d699
    

    In the CodePen demo below, I’ve connected a function to an HTML button so that the background color of the document changes whenever the button is clicked.

    look at the pen
    Random Color – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Random letter generation

    We already have functions to create random integers, but what about random characters? Fortunately, there’s a nice way to convert integers to characters using a base. In base 36, the integers 10 through 35 are represented by the letters ‘a’ through ‘z’. This can be verified by converting some values ​​to base 36 in the console. toString Method:

    (24).toString(36)
    (16).toString(36)
    

    Knowing this, it’s easy to write: randomLetter functions that use us randomInt A function that generates a random integer between 10 and 35 and returns its base 36 string representation:

    function randomLetter(){
     return randomInt(10,35).toString(36)
    }
    

    talking randomLetter I need to return a random lowercase letter from ‘a’ to ‘z’.

    randomLetter()
    << "o"
    
    randomLetter()
    << "g"
    

    I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

    look at the pen
    Random Letters – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random string

    Now that we can create random characters, we can combine them to create random strings.let’s write randomString a function that accepts a single parameter, n — This represents the number of random characters you want in the returned string.You can create random strings by creating an array or length n and, map A method that changes each element to a random character. next, join A method to convert an array to a random string:

    function randomString(numberOfLetters){
      return [...Array(numberOfLetters)].map(randomLetter).join``
    }
    

    talking randomString(n) should return a random string of n letter:

    randomString(5)
    << "xkibb"
    
    randomLetter(3)
    << "bxd"
    

    I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

    look at the pen
    Random String – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    select a random element from an array

    It is often useful to be able to select random elements from an array.This can be done fairly easily using our randomInt function. You can randomly choose an index in an array by using the length of the array as an argument and returning the element at that index from the array.

    function randomPick(array){
     return array[randomInt(array.length)]
    }
    

    For example, with the following array representing a list of fruits:

    const fruits = ["🍏",🍌","🍓","🥝","🍋","🍐","🫐","🍉"]
    

    You can use the following code to pick a fruit randomly.

    randomPick(fruits)
    << "🍉"
    

    generate random phrases

    Now that we have a function that selects a random element from the array, we can use it to create a random phrase. This technique is often used as placeholder usernames on websites. First, create three arrays as shown below. One contains adjective strings, one contains colors, and other nouns.

    const adjectives = ["Quick","Fierce","Ugly","Amazing","Super","Spectacular","Dirty","Funky","Scary"]
    const colors = ["Brown","Red","Orange","Black","White","Purple","Pink","Yellow","Green","Blue"]
    const nouns = ["Fox","Bear","Monkey","Hammer","Table","Door","Apple","Banana","Chair","Chicken"]
    

    Now that we have these three sequences, it’s easy to create random phrases. randomPick function. Select random elements from each array, concatenate them, and put a space between them to create a clause.

    function randomPhrase(a,c,n){
      return `${randomPick(a)} ${randomPick(c)} ${randomPick(n)}`
    }
    

    talking randomPhrase It should return a slightly funny-sounding random phrase containing colors, adjectives, and nouns.

    randomPhrase()
    << "Funky Pink Chicken"
    

    I’ve hooked this function up to an HTML button, so you can create some wacky phrases by pressing the button in the CodePen demo below.

    look at the pen
    Random Phrase – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Generate random password

    The final use of random integers we’ll look at is generating random password strings. A general rule for passwords is that they contain at least:

    • 8 characters
    • one number
    • 1 non-alphanumeric special character

    Examples that fit these rules are:

    secret!1
    

    We already have a function that can generate each of these elements.First, use randomString(6) Create a random string of 6 characters. next, randomPick Use a function to select special characters from an array, then use randomInt(9) Returns a random number. Now just concatenate them together and you have a randomly generated password!

    You can boil this down to a function that returns a random password string.

    function generatePassword(){
      return randomString(6) + randomPick(["!","%","?","&","@","£","$","#"]) + randomInt(9)
    }
    

    talking generatePassword It should return a random password that passes the above three rules.

    generatePassword()
    << "ykkefn@8"
    

    Now that you’ve connected this function to an HTML button, try pressing the button to generate a random password in the CodePen demo below.

    look at the pen
    Random Password – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    One thing to note is how all the functions we’ve written so far are randomInt the first function I wrote.of generatePassword For example, the function we just wrote is randomInt,randomPick and randomString function…and randomString the function is randomLetter function! This is the foundation of programming, using functions as building blocks for more complex functions.

    summary

    We’ve seen how to generate random numbers in JavaScript. I hope you find this guide helpful.of randomInt The function is certainly a nice function to have in your locker and can help add some randomness to your project.

    You can see all the examples covered in this article in the following CodePen demos.

    look at the pen
    Randomness – SitePoint by SitePoint (@SitePoint)
    with a code pen.

    Related reading:



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleBrendan Eich: Don’t Blame Cookies and JavaScript
    Next Article The Daily Herald – K1 Britannia Foundation launches support program for troubled youth
    websitebuildersnow
    • Website

    Related Posts

    Burp Suite Enterprise Edition Power Tools: Unleash the Power of Command Line, Python and More | Blog

    March 21, 2023

    Forms: Run function when field changes? – JavaScript – SitePoint Forum

    March 20, 2023

    TypeScript 5 – Smaller, Simpler, Faster

    March 20, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    8 Best Tents (2023): Backpacking, Family, and Ultralight

    March 21, 2023

    Cost of living: How can I save money on my food shop?

    March 21, 2023

    Man charged over abusive email to Angela Rayner

    March 21, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.