«

Math的random方法

yang 发布于 阅读:402 JS基础阶段


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            // Math.random() 获取0~1之间的随机小数,包含0不包含1
            console.log(Math.random());

            // 求0~10之间的随机整数
            // 问题1:使用floor向下取整,永远到达不了1
            console.log(Math.floor(Math.random() * 10));
            // 问题2:使用ceil向上取整,永远到达不了0
            for (let i = 0; i < 10000; i++) {
                if (Math.ceil(Math.random() * 10) === 0) {
                    console.log("有0");
                } else {
                    console.log("没有0");
                }
            }
        </script>
    </body>
</html>

Math的random方法

版权所有:微4e
文章标题:Math的random方法
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论