var textArray = [
'song1.ogg',
'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
audioElement.setAttribute('src', textArray[randomNumber]);
Answer from Gideon on Stack Overflowvar textArray = [
'song1.ogg',
'song2.ogg'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
audioElement.setAttribute('src', textArray[randomNumber]);
var randomIndex = Math.floor(Math.random() * textArray.length);
var randomElement = textArray[randomIndex];
I am new to programming because of my school but how can I make the program choose a random String of the available Strings i have given to him. How can i lead this whole process from beginning to the end I am actually confused because I tried something with array and java.util.Random, but it seems to only do the work with integers in "x"
Thank youu
Videos
this fiddle works.
var myArray = ['January', 'February', 'March'];
var rand = Math.floor(Math.random() * myArray.length);
function showquote(){
document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();
the problem is with this line
var rand = myArray[Math.floor(Math.random() * myArray.length)]; // dereferenced myArray[] twice here
The problem is that rand' is already the value from the array (e.g. "January"),
var rand = myArray[Math.floor(Math.random() * myArray.length)];
so you cannot get value from the array again using myArray['January'].
You should change your Js function as below
function showquote(){
document.getElementById('quote').innerHTML = rand;
}
Or change your variable
var rand = Math.floor(Math.random() * myArray.length);
It's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
If you've already got underscore or lodash included in your project you can use _.sample.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
If you need to get more than one item randomly, you can pass that as a second argument in underscore:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
or use the _.sampleSize method in lodash:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);