How can I get a random variable , taking a series of these:
var a = 'HFKDJ3';
var b = 'JFI393';
var c = 'KMMMFN';
How can I show by document.write
any of those variables, but randomly,
How can I get a random variable , taking a series of these:
var a = 'HFKDJ3';
var b = 'JFI393';
var c = 'KMMMFN';
How can I show by document.write
any of those variables, but randomly,
You can put them in an array and make the classic Math.floor(Math.random() * myArray.length)
var a = 'HFKDJ3';
var b = 'JFI393';
var c = 'KMMMFN';
var arr = [a,b,c];
console.log(arr[Math.floor(Math.random() * arr.length)]);
Here is an example where:
I create an array of texts with the 3 texts. Pressing the button I call the random function that calculates a random number between 0 and 2 and returns the corresponding text. Show an alert with the text returned.
EDITO
I modify the code to use objects so that the function not only returns the text but also the key of the selected value.
var textos = [
{key: 'a', value: 'HFKDJ3'},
{key: 'b', value: 'JFI393'},
{key: 'c', value: 'KMMMFN'}
];
function aleatorio(){
var indice = Math.floor((Math.random() * 3));
var el = textos[indice];
return el.key + ': ' + el.value;
}
<input type="button" value="aleatorio" onclick="alert(aleatorio());" />