javascript - 如何生成 2 个随机数?为什么我的方法不起作用?

标签 javascript math

我目前正在尝试学习 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/

相关文章:

javascript - 如何在 Volt 中实现客户端 javascript (jquery .animate)?

javascript - 通过 JQuery 下载 .EXE 文件

javascript - 如何使用vue js滚动结束页面

math - 将线性音频分布转换为对数/感知分布?

algorithm - 如何生成伪随机对合?

javascript - 创建包含数组中超链接项的下拉列表

javascript - clearTimeout 不起作用 - setinterval 问题

javascript - 将百分比添加到数字

python - python中的多维卷积

algorithm - 计算两个经纬度点之间的距离? (哈弗斯公式)