Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you select a random variable within a function in JavaScript?

Tags:

javascript

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.

like image 542
Eddie Vartanessian Avatar asked Jul 18 '26 15:07

Eddie Vartanessian


2 Answers

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.)

like image 133
nnnnnn Avatar answered Jul 21 '26 06:07

nnnnnn


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]);
}
like image 33
Mortalus Avatar answered Jul 21 '26 04:07

Mortalus