Sponsor

LightBlog

Tuesday 27 December 2016

House Of Tricks 2017 Gift From Tricks Bytes

Select Random Item from an ArrayThis is super succicnt, and here I was doing this all the time like a total schmo…

var myArray = [ "Apples", "Bananas", "Pears" ]; var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
JS Result
EDIT ON
function randomNum(minVal, maxVal) {
do {
r = Math.random();
} while (r == 1);
return minVal+Math.floor(r*(maxVal+1-minVal));
}
var coolwords = new Array();
coolwords[0] = “robot”;
coolwords[1] = “inferno”;
coolwords[2] = “giga”;
coolwords[3] = “infinity”;
coolwords[4] = “pow”;
coolwords[5] = “smash”;
coolwords[6] = “boom”;
coolwords[7] = “crunch”;
coolwords[8] = “robot”;
coolwords[9] = “inferno”;
document.body.innerHTML = coolwords[randomNum(0, coolwords.length-1)];
var myArray = [
  "Apples",
  "Bananas",
  "Pears"
];

var randomItem = myArray[Math.floor(Math.random()*myArray.length)];

document.body.innerHTML = randomItem;

No comments:

Post a Comment