Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  138] [ 2]  / answers: 1 / hits: 17801  / 12 Years ago, sun, january 20, 2013, 12:00:00

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.


More From » javascript

 Answers
37

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


[#80751] Friday, January 18, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mickaylag

Total Points: 333
Total Questions: 108
Total Answers: 93

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;