你如何在 JavaScript 的函数中选择一个随机变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14422233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you select a random variable within a function in JavaScript?
提问by Eddie Vartanessian
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.
我在一个函数中放置了多个变量,我想知道 JavaScript 中是否有可能在该函数中随机选择一个变量。任何帮助是极大的赞赏。太感谢了。
回答by nnnnnn
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/
演示: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.)
(当然,数组不必包含像我展示的字符串那样的简单值,你可以有一个对象数组,或对其他函数的引用等。)
回答by Mortalus
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]);
}
回答by jfriend00
If you have N variables, then it is cleanest to put them in an array and generate a random index into that array.
如果您有 N 个变量,那么将它们放在一个数组中并在该数组中生成一个随机索引是最干净的。
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.
如果您只有几个变量,则可以生成一个随机数并使用if/else
语句对所需变量进行操作。
var a, b;
var index = Math.random();
if (index < 0.5) {
// operate on a
a = 3;
} else {
// operate on b
b = 3;
}