我目前正在尝试学习 JavaScript,并想编写一个生成 2 个随机整数的程序。我的尝试如下
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Generate</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = Math.floor((Math.random() * 10) + 1);
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x ", " y;
}
</script>
</body>
</html>
但是,这不起作用。谁能解释我做错了什么?当我只有 x 时它有效,但当我有 x 和 y 时则无效。
最佳答案
看看这个
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Generate</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x = Math.floor((Math.random() * 10) + 1);
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x + ", " + y;
}
</script>
</body>
</html>
问题是:
x ", " y
正确的方法:
x + ", " + y
关于javascript - 如何生成 2 个随机数?为什么我的方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34206574/