JS-Math对象的常用方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math对象的常用方法</title>
</head>
<body>
    <script>
        var num1 = 9.1
        var num2 = 9.5
        var num3 = 9.49999
        console.log(Math.ceil(num1));    //打印:10
        console.log(Math.floor(num1));    //打印:9
        console.log(Math.round(num2));    //打印:10
        console.log(Math.round(num3));    //打印:9


        var num4 = Math.random();
        console.log(num4);    //得到一个随机的数字,这个数字是0 ~ 1之间的值,包含0 ,但是不包含1,比如:0.8624888975105858
        //获取0 ~ 4整数
        var num5 = Math.random() * 4;
        console.log(num5)    //随机打印0~4,比如:1.808445726112911
        /*
            问题
                1. 小数太多了
                2. 不包含4
        */
        console.log(Math.ceil(num5))    //4 0出现概率太低
        console.log(Math.floor(num5))    // 3 不可能拿到4
        console.log(Math.round(num5))    //OK
        /*
            0 ~ n
                包含n ,使用round
                不包含n ,推荐使用floor

            5 ~ 10 -5
                Math.random() * 10 // 0 ~ 10
            0 ~ 5
                Math.random() * 5 //0 ~ 5  5 ~ 10

            2 ~ 17 - 2
            0 ~ 15
                Math.random() * 15 + 2
        */




        /*
            Math.max()
                返回是当前一组数中最大的值
                如果不给参数,返回-Infinity
            Math.min()
                返回当前数组中最小的值
                如果不给参数,返回Infinity
                
            以上两个方法,在内部都会执行Number,如果是不可以转成有效值的,会返回NaN

        */
        console.log(Math.max(10,50,15,20,60));    //打印:60
        console.log(Math.max());    //打印:-Infinity

        console.log(Math.min(10, 50, 15, 20, 60));    //打印:10
        console.log(Math.min());    //打印:Infinity
        console.log(Math.max('5','66'));    //打印:66
        console.log(Math.max('5','a'));    //打印:NaN
          
    </script>
</body>
</html>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值