how to get a random element of an array javascript
var foodItems = ["Bannana", "Apple", "Orange"];
var theFood = foodItems[Math.floor(Math.random() * foodItems.length)];
/* Will pick a random number from the length of the array and will go to the
corosponding number in the array E.G: 0 = Bannana */
function RandomItemFromArray(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)]
}
var fruit = [ "Apples", "Bananas", "Pears", ];
let fruitSample = RandomItemFromArray(fruit)
// 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
//Make all arrays have "random" method
Array.prototype.random = function() {
return this[Math.floor(Math.random() * this.length)];
}
//Call "random" method on an array
var result = ["Hello", "world"].random();
how to get a random statement from an array in javascript
// List your array items
let Testing1 = ["put","things","here"]
let Generate = Math.floor((Math.random() * Testing1.length)); // Generates a number of the array.
// logs the result
console.log(Testing1[Generate])
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
Run code snippetHide results