JavaScript arrays are probably my favorite primitive in JavaScript. You can do all sorts of awesome things with arrays: get unique values, clone them, dump them, etc. What about getting a random value from an array?
To get a random element from an array you can use 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 to when you would need random values from an array, that depends on your individual application. It’s good to know, however, that you can easily get a random value. Should Array.prototype.random
to exist?
Camera and video control with HTML5
Client-side APIs on mobile and desktop devices quickly deliver the same APIs. Of course, our mobile devices had access to some of these APIs first, but these APIs are slowly making their way to the desktop. One of these APIs is the getUserMedia API…
Web Notifications API
Every UI framework has the same set of widgets that have become almost essential to modern sites: modals, tooltips, button varieties, and notifications. One problem I find is that each site has its own colors, widget styles, etc. – users do not get a consistent experience. Apparently the…
HTML5’s window.postMessage API
One of the little-known HTML5 APIs is the window.postMessage API.
window.postMessage
allows to send data messages between two windows/frames through domains. Essentially, window.postMessage acts like cross-domain AJAX without the server shims. let’s see howwindow.postMessage
works and how you…