In Javascript, how does one declare a variable to be a random element from a predefined finite set of values? For example, suppose a user wants to assign the variable fooBar to be a random element from the set {1, 2, 3}. How would one do this?
Asked
Active
Viewed 35 times
0
George
- 6,927
- 4
- 34
- 67
1 Answers
0
From an object:
function pickRandomProperty(obj) {
var result;
var count = 0;
for (var prop in obj)
if (Math.random() < 1/++count)
result = prop;
return result;
}
From an array:
var rand = myArray[Math.floor(Math.random() * myArray.length)];
Alex J
- 1,029
- 6
- 8