Math 和 Date 对象

Math 和 Date 对象

1. Math 对象

Math 是一个内置对象,它拥有一些数学常数属性和数学函数方法。Math 不是一个函数对象

Math 不是一个构造器,Math 的所有属性与方法都是静态的

Math 用于 Number类型,它不支持 bigInt 类型

方法 描述
Math.PI 圆周率,Math 对象的属性
Math.abs() 返回绝对值
Math.random() 生成0 ~ 1之间的随机浮点数
Math.floor() 向下取整(往小取值)
Math.ceil() 向上取整(往大取值)
Math.trunc() 移除小数点后的所有内容而没有舍入
Math.round() 四舍五入取整(正数四舍五入,负数五舍六入)
Math.max(x, y, z) 返回多个数中的最大值
Math.min(x, y, z) 返回多个数中的最小值
Math.pow(x,y) 乘方:返回 x 的 y 次幂
Math.sqrt() 开方:对一个数进行开方运算

2. 舍入

2-1 Math.floor()

Math.floor(num)

向下舍入往小取值:3.1 变成 3-1.1 变成 -2

console.log(Math.floor(2.9)); // 2
console.log(Math.floor(-1.1)); // -2

2-2 Math.ceil()

Math.ceil(num)

向上舍入往大取值:3.1 变成 4-1.1 变成 -1

console.log(Math.ceil(2.9)); // 3
console.log(Math.ceil(-1.1)); // -1

2-3 Math.round()

Math.round(num)

四舍五入取整,正数四舍五入,负数五舍六入

向最近的整数舍入:3.1 变成 33.6 变成 4,中间值 3.5 变成 4

console.log(Math.round(2.9)); // 3
console.log(Math.round(-1.1)); // -1

2-4 Math.trunc()

Math.trunc(num) IE浏览器不支持

移除小数点后的所有内容而没有舍入:3.1 变成 3-1.1 变成 -1

console.log(Math.trunc(2.9212)); // 2
console.log(Math.trunc(-1.112)); // -1

3. 其它数学函数

3-1 Math.random()

Math.random()

返回一个从 0 到 1 的随机数(不包括 1)

 console.log(Math.random());

 // 两个数中的随机数
 function getRandomArbitrary(min, max) {
   
 	return Math.random() * (max - min) + min;
 }
 console.log(getRandomArbitrary(1, 3));

 // 两个数之间的随机整数
 function getRandomInt(min, max) {
   
 	min = Math.ceil(min);
 	max = Math.floor(max);
 	return Math.floor(Math.random() * (max - min)) + min; 
     //不含最大值,含最小值
 }
 console.log(getRandomInt(1, 8));

 // 两个数之间的随机整数 包括两个数
 function getRandomIntInclusive(min, max) {
   
 	min = Math.ceil(min);
 	max = Math.floor(max);
 	return Math.floor(Math.random() * (max - min + 1)) + min; 
     //含最大值,含最小值 
 }
 console.log(getRandomIntInclusive(1, 8));

3-2 Math.max() & Math.min()

Math.max(a, b, c...)Math.min(a, b, c...)

从任意数量的参数中返回最大/最小值

// 在任意参数值返回最大值
console.log(Math.max(2, 4, 7)); // 7
console.log(Math.max(2, 4, 7.5)); // 7.5
        
// 在任意参数值返回最小值
console.log(Math.min(2, 4, 7, 10, 1)); // 1

3-3 Math.pow()

Math.pow(n, power)

返回 n 的给定 power 次幂

// 幂
console.log(Math.pow(2, 4)); // 16

3-4 Math.abs()

Math.abs(x)

返回指定数字的绝对值
Math.abs ⁡ ( x ) = ∣ x ∣ = { x if x ≥ 0 − x if x < 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值