Math对象

Math对象是JavaScript的内置对象,提供一系列的数学常数和数学方法。Math对象只提供了静态的属性和方法,所以使用时,不需要实例化。

JS对象的分类:

内部对象:

  • js中的内部对象包括Array、Boolean、Date、Function、Global、Math、Number、Object、RegExp、String以及各种错误类对象,包括Error、EvalError、RangeError、ReferenceError、SyntaxError和TypeError。
  • 其中Global和Math这两个对象又被称为“内置对象”,这两个对象在脚本程序初始化时被创建,不必实例化这两个对象。

宿主对象

  • 宿主对象就是执行JS脚本的环境提供的对象。对于嵌入到网页中的JS来说,其宿主对象就是浏览器提供的对象,所以又称为浏览器对象,如IE、Firefox等浏览器提供的对象。不同的浏览器提供的宿主对象可能不同,即使提供的对象相同,其实现方式也大相径庭!这会带来浏览器兼容问题,增加开发难度。 浏览器对象有很多,如Window和Document,Element,form,image,等等。

自定义对象

  • 顾名思义,就是开发人员自己定义的对象。JS允许使用自定义对象,使JS应用及功能得到扩充

Math对象的属性

Math对象提供以下一些只读的数学常数。

  • Math.E // 2.718281828459045(自然底数 无限不循环小数)lim(1+1/n)^n=e ,n→+∞
  • Math.LN2 // 0.6931471805599453(2的自然对数)
  • Math.LN10 // 2.302585092994046(10的自然对数)
  • Math.LOG2E // 1.4426950408889634(2为底 e的对数)
  • Math.LOG10E // 0.4342944819032518
  • Math.PI // 3.141592653589793
  • Math.SQRT1_2 // 0.7071067811865476
  • Math.SQRT2 // 1.4142135623730951

练习:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Math对象的属性</title>
</head>
<body>
<h2>请输入你家花园的半径 单位是m</h2>
<input type="text" id="ipt">
<h2>你家花园的面积是 <span id="area"></span>,  你家花园的周长是 <span id="length"></span></h2>
<script>
    // 获取π
    console.log(Math.PI);
    //获取自然底数
    console.log(Math.E);
    //获取2的和1/2平方根
    console.log(Math.SQRT2);
    console.log(Math.SQRT1_2);

    // 练习
    var oIpt = document.getElementById("ipt");
    var oArea = document.getElementById("area");
    var oLength = document.getElementById("length");
    oIpt.onchange = function () {
        oArea.innerHTML = Math.PI * oIpt.value * oIpt.value;
        oLength.innerHTML = 2 * Math.PI * oIpt.value;
    }
</script>
</body>
</html>

Math对象的方法

  • Math.abs():求绝对值 对一个数字进行绝对值操作,并且也能对纯数字的字符串操作
  • Math.ceil():向上取整 向大的数值取整
  • Math.floor():向下取整 向小的数值取整
  • Math.round():四舍五入,四舍五入是对小数点的后一位进行判断
    • 正数的时候,当小数点后一位大于等于5的时候 整数部分加1 小于5的时候 整数部分不变
    • 负数的时候 当小数点后一位 大于5的时候 整数减1 小于5的时候 整数不变
    • 负数的时候 当小数点后一位是5 后边没有第二个小数位了 整数不变;如果5后还有小数位 那么 整数减1
  • Math.min()和Math.max() 计算一组数值中的最大值和最小值
  • pow:返回以第一个参数为底数,第二个参数为幂的指数值
  • sqrt: 返回参数的平方根,如果参数是负数,返回NaN
  • sin cos tan
  • Math.random():求随机数 生成 [0,1) (大于等于0 小于1) 小数随机数
console.log(Math.abs(4));;//4
console.log(Math.abs(-4));;//4
console.log(Math.abs(-Infinity));;//Infinity
console.log(Math.abs("-3px"));;//NaN
console.log(Math.abs("-3"));;//3

console.log(Math.ceil(3.1));//4
console.log(Math.ceil(3.5));//4
console.log(Math.ceil(-3.1));//-3
console.log(Math.ceil(-3.5));//-3

console.log(Math.floor(3.1));//3
console.log(Math.floor(3.5));//3
console.log(Math.floor(-3.1));//-4
console.log(Math.floor(-3.5));//-4

console.log(Math.round(3.1));;//3
console.log(Math.round(3.5));;//4
console.log(Math.round(3.55));;//4
console.log(Math.round(3.6));;//4
console.log(Math.round(-3.1));;//-3
console.log(Math.round(-3.5));;//-3
console.log(Math.round(-3.51));;//-4
console.log(Math.round(-3.6));;//-4

console.log(Math.max(45, 32, 45, 65, 12, 3, 8, 45, 33));
console.log(Math.min(45, 32, 45, 65, 12, 3, 8, 45, 33));

console.log(Math.pow(2, 200));
console.log(Math.pow(2.1, 200));

// 1度的弧度 :2 * Math.PI / 360
console.log(Math.sin(30 * 2 * Math.PI / 360));

console.log(Math.sqrt(4));

setInterval(function () {
    console.log(Math.random());
},300)

随机数练习

  • 得到[a,b)的随机数
  • 得到一个随机字符串
  • 如何得到一个随机的IP地址:0.0.0.0~255.255.255.255
  • 有一半的几率在做什么事情,另一半的几率在做另一件事
//得到[a,b)的随机数
function random(a,b) {
 return a + Math.floor(Math.random()*(b-a));
}

// 得到一个随机字符串
function randomStr(len){
    var dict = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    var str = '';
    for(var i = 0; i < len; i ++){
        str += dict[random(0,62)]//获取数组的下表所对应的元素
    }
    return str;
}

//如何得到一个随机的IP地址:0.0.0.0~255.255.255.255
function randomIP(len){
    var arr = []
    for(var i = 0; i < 4; i++){
        arr.push(random(0,256));
    }
    return arr.join('.');
}

//有一半的几率在做什么事情,另一半的几率在做另一件事
if(Math.random() > 0.5){
    console.log('haha');
}else{
    console.log('ninini');
}

小球曲线运动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球曲线运动</title>
    <style>
        #box{
            width: 20px;
            height: 20px;
            background-color: red;
            border-radius: 50%;

            position: fixed;
            left: 20px;
            top: 300px;
        }
    </style>
</head>
<body>
    <div id="box">

    </div>
    <script>
        var oBox = document.getElementById("box");
        var timer = null;
        var degStart = 0;
        timer = setInterval(function () {
            degStart ++;
            oBox.style.left = 20 + degStart + "px";
            oBox.style.top = 300 + Math.sin(degStart * 2 * Math.PI / 360)*100 + "px";
        },10)
    </script>
</body>
</html>

小球曲线运动路径版

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球曲线运动</title>
    <style>
        #box{
            width: 20px;
            height: 20px;
            background-color: red;
            border-radius: 50%;

            position: fixed;
            left: 20px;
            top: 300px;
        }
        .show{
            width: 20px;
            height: 20px;
            background-color: red;
            border-radius: 50%;
            position: fixed;
        }
    </style>
</head>
<body>
    <div id="box">

    </div>
    <script>
        var oBox = document.getElementById("box");
        var timer = null;
        var degStart = 0;
        timer = setInterval(function () {
            var newBox = document.createElement("div");
            newBox.className = "show";
            document.body.appendChild(newBox);
            degStart ++;
            newBox.style.left = 20 + degStart + "px";
            // newBox.style.top = 300 + Math.sin(degStart * 2 * Math.PI / 360)*100 + "px";
            // newBox.style.top = 300 + -Math.abs(Math.sin(degStart * 2 * Math.PI / 360)*100) + "px";
            newBox.style.top = 300 + -(Math.sin(degStart * 2 * Math.PI / 360)*100) + "px";
        },10)
    </script>
</body>
</html>

点名器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>点名器</title>
    <style>
        body{
            background-color: #0D1635;
        }
        h2{
            font-size: 70px;
            color: yellow;
            text-align: center;
        }
        p{
            font-size: 60px;
            color: #fff;
            text-align: center;
        }
    </style>
</head>
<body>
    <h2 id="btn">start</h2>
    <p id="con">开始点名</p>
    <script>
        var oBtn = document.getElementById("btn");
        var oCon = document.getElementById("con");
        var names = ["陈纪法","张三","李四","胡宝林","柏洪洋"];
        var flag = true;//保存当前停止状态
        var timer = null;
        oBtn.onclick = function () {
            if(flag){
                oBtn.innerHTML = "stop";
                timer = setInterval(function () {
                    // names中的值应该是[0,4]  [0,5)
                    oCon.innerHTML = names[Math.floor(Math.random()*names.length)];
                },30)
            }else{
                oBtn.innerHTML = "start";
                clearInterval(timer);
            }

            flag = !flag;
        }
    </script>
</body>
</html>
posted @ 2023-01-12 21:53  z_bky  阅读(167)  评论(0)    收藏  举报