WebMasterCampus
WEB DEVELOPER Resources

Javascript Get a Random Item From Array

Javascript Get a Random Item From Array


Javascript Get a Random Item From Array

Solution 1

var item = items[Math.floor(Math.random()*items.length)];

Solution 2

First Define Array prototype.

Array.prototype.random = function () {
  return this[Math.floor((Math.random()*this.length))];
}

then use it with inline or predefined arrays.

[22,33,44, 55].random()


var list = [99, 88, 77, 66, 55]
list.random()

Solution 3 using Function

function get_random (list) {
  return list[Math.floor((Math.random()*list.length))];
}


get_random([12, 13, 14, 31, 42])
Created with love and passion.