Wednesday, April 24, 2024
HomeTechnologySoftwareGet a Random Array Item with JavaScript

Get a Random Array Item with JavaScript

Date:

Related stories

spot_imgspot_img

JavaScript Arrays are probably my favorite primitive in JavaScript. You can do all sorts of awesome things with arrays: get unique values, clone them, empty them, etc. What about getting a random value from an array?

To get a random item from an array, you can employ Math.random:

const arr = [
    "one",
    "two",
    "three",
    "four",
    "tell",
    "me",
    "that",
    "you",
    "love",
    "me",
    "more"
];
const random1 = arr[(Math.floor(Math.random() * (arr.length)))]
const random2 = arr[(Math.floor(Math.random() * (arr.length)))]
const random3 = arr[(Math.floor(Math.random() * (arr.length)))]
const random4 = arr[(Math.floor(Math.random() * (arr.length)))]

console.log(random1, random2, random3, random4)
// tell one more two

As for when you would need random values from an array is up to your individual application. It’s nice to know, however, that you can easily get a random value. Should Array.prototype.random exist?

  • An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer…

  • Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called “parallax” effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a…



Source link

Latest stories

spot_img
Previous articleHow I use Twitter
Next articlephotostream 128