I have put multiples variables within a function and I was wondering if there was any way possible in JavaScript to select a variable within that function at random. Any help is greatly appreciated. Thank you so much.
If you use an array instead of multiple variables then you can select a random element from the array:
function test() {
var values = ["test","values","go","here"],
valueToUse = values[Math.floor(Math.random() * values.length)];
// do something with the selected value
alert(valueToUse);
}
Demo: http://jsfiddle.net/XDn2f/
(Of course the array doesn't have to contain simple values like the strings I showed, you could have an array of objects, or references to other functions, etc.)
If one of your parameters is an array you can randomly select one value from it.
function myFunc(arrayInput)
{
var randomIndex = Math.floor((Math.random()*10)+1);
return (arrayInput[randomIndex]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With