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.
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.
Share Improve this question asked Jan 20, 2013 at 6:21 Eddie VartanessianEddie Vartanessian 651 gold badge1 silver badge8 bronze badges3 Answers
Reset to default 11If 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/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 have N variables, then it is cleanest to put them in an array and generate a random index into that array.
var items = [1,2,3,4];
var index = Math.floor(Math.random() * items.length);
items[index] = whatever;
If you only have a couple variables, you can generate a random number and use an if/else
statement to operate on the desired variable.
var a, b;
var index = Math.random();
if (index < 0.5) {
// operate on a
a = 3;
} else {
// operate on b
b = 3;
}