可能重复:
从JavaScript数组中获取随机值
好的,所以我这里有三个变量,每个变量都是摇滚,纸张或剪刀.使用JavaScript,我如何随机生成其中一个单词?
到目前为止它是这样的:
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="myFunction()"> Click me</button>
<script>
function myFunction()
{
var c="Rock";
var d="Paper";
var e="Scissors";
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
然后我将有一个名为K的变量,它将是岩石纸或剪刀中的随机单词.所以它会是这样的:
alert("The computer chose: " + k);
Run Code Online (Sandbox Code Playgroud)
那么如何让JavaScript在三个变量之间随机选择c,d和e?
Den*_*ret 23
使用:
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);
Run Code Online (Sandbox Code Playgroud)
只是为了准确回答你的问题,假设你真的想保留你的三个全局变量,你可以这样做:
var c = "Rock";
var d = "Paper";
var e = "Scissors";
var thing = window['cde'.charAt(Math.floor(Math.random()*3))];
document.write('The computer chose: ' + thing);
Run Code Online (Sandbox Code Playgroud)
(但不要.)