Javascript Math random() get random item from array

Description

Javascript Math random() get random item from array

function selectFrom(lowerValue, upperValue) {
    let choices = upperValue - lowerValue + 1;
    return Math.floor(Math.random() * choices + lowerValue);
}
let num = selectFrom(2, 10);
console.log(num); // number between 2 and 10, inclusive 

let colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"]; 
let color = colors[selectFrom(0, colors.length-1)]; 
console.log(color);/*from w w  w  .  j av a2 s  . c  o  m*/
color = colors[selectFrom(0, colors.length-1)]; 
console.log(color);
color = colors[selectFrom(0, colors.length-1)]; 
console.log(color);



PreviousNext

Related