javascript generate random array code example
Example 1: javascript get random array value
//get random value from array
var colors = ["red","blue","green","yellow"];
var randColor = colors[Math.floor(Math.random() * colors.length)];
Example 2: Javascript get random item from array
var colors = ["red","blue","green","yellow"];
var randomColor = colors[Math.floor(Math.random()*colors.length)]; //pluck a random color
Example 3: javascript how to get a random element from an array
var items = ['Yes', 'No', 'Maybe'];
var item = items[Math.floor(Math.random() * items.length)];
Example 4: how do you make a random array in javascript
// how to generate random words from an array
const Coins = ["Heads","Tails"]
let Generate = Math.floor((Math.random() * Coins.length));
console.log(Coins[Generate]) // this will print the outcome
Example 5: javascript generate random array
//This example is to generate an array with 40 random elements, with random values from 0 to 39
for (var a=[],i=0;i<40;++i) a[i]=i;
// http://stackoverflow.com/questions/962802
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);