Get a Random Array Item with JavaScript
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?
Contents
Regular Expressions for the Rest of Us
Sooner or later you’ll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In…
Introducing MooTools Templated
One major problem with creating UI components with the MooTools JavaScript framework is that there isn’t a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven…
Duplicate the jQuery Homepage Tooltips Using MooTools
The jQuery homepage has a pretty suave tooltip-like effect as seen below: Here’s how to accomplish this same effect using MooTools. The XHTML The above XHTML was taken directly from the jQuery homepage — no changes. The CSS The above CSS has been slightly modified to match the CSS rules already…
Chris Coyier’s Favorite CodePen Demos II
Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so…
[ad_2]
Source link