JavaScript学习 第二课(二)

JavaScript学习 第二课(二)

一、Math对象

该对象的作用是用来处理数学运算符的,该对象不需要手动创建,因为它是window对象的一个属性,当页面加载完毕后,后台就是自动创建Math对象,可以采用window.Math阿里使用。或者省略window对象,直接使用Math。

二、Math的常用属性—PI
1、作用:获取圆周率
2、格式:Math.PI
在这里插入图片描述
在这里插入图片描述
三、Math的常用方法

1)、round 方法:
作用:对数据进行四舍五入
格式: Math.round(数据);
返回值:返回数据的整数部分,即该方法在对数据进行四舍五入时是对小数点后一位进行处理。

  console.log(Math.round(3.14));

在这里插入图片描述

2)、ceil方法:
作用:对数据进行向上取整,取最小的整数
格式:Math.ceil(数据);
返回值:比数据大的最小的整数

  console.log(Math.ceil(3.74));

在这里插入图片描述
3)floor方法:
作用:对数据进行向下取整,取最大的整数
格式:Math.floor(数据);

console.log(Math.floor(3.74));

4)、random方法:
作用:生成0-1的随机数字,包含0,但是不包含1
格式:Math.random();
注意:
1):如果要生成n-m,且包含n和m的随机整数:

 parseInt(Math.random()*(最大值+1-最小值)+最小值);

2):如果要生成数组的随机下标或者字符串的随机下标:

 parseInt(Math.random() *数组.length);

        console.log(Math.random());

在这里插入图片描述
在这里插入图片描述

5) 、max 方法:
作用;求一组数据的最大值
格式:Math.max(值1,值2,值3…);

6)、min方法:

作用:求一组数据当中的最小值
格式:Math.min(值1,值2,值3…);

      console.log(Math.min(1, 2, 4, 7, 10));
        console.log(Math.max(10, 4, 5, 90));

在这里插入图片描述
7)、abs方法:
作用:求数据的绝对值
格式:Math.abs(值);
返回值:数据的绝对值;

        console.log(Math.abs(-1));

在这里插入图片描述

8)、pow方法

作用:求x的y次方
格式:Math.pow(x,y);

  console.log(Math.pow(2, 10));

在这里插入图片描述

9)、sqrt方法:
作用:求数据的算数平方根
格式:Math.sqrt(数据);

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

在这里插入图片描述
四、toFixed方法
作用:对一个数据的小数位数进行处理
格式:数据.toFixed(小数位数);
注意:该方法的返回值是字符串类型

        var num = Math.PI;
        var res = num.toFixed(3);
        console.log(res);
        console.log(typeof res);

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46374969/article/details/115268437