Math对象(常用的)

1.1Math.max(),Math.min()

Math.max方法返回参数中最大的那个值,Math.min返回最小的那个值,如果参数为空,Math.min返回Infinity, Math.max返回-Infinity

Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity复制代码

2.Math.floor(),Math.ceil()

Math.floor方法向下取整,Math.ceil方法向上取整

Math.floor方法小于参数值的最大整数(地板值)。

Math.floor(3.2) // 3
Math.floor(-3.2) // -4复制代码

Math.ceil方法返回大于参数值的最小整数(天花板值)。

Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3复制代码

这两个方法可以结合起来,实现一个总是返回数值的整数部分的函数。

function ToInteger(x) {
  x = Number(x);
  return x < 0 ? Math.ceil(x) : Math.floor(x);
}

ToInteger(3.2) // 3
ToInteger(3.5) // 3
ToInteger(3.8) // 3
ToInteger(-3.2) // -3
ToInteger(-3.5) // -3
ToInteger(-3.8) // -3复制代码

上面代码中,不管正数或负数,ToInteger函数总是返回一个数值的整数部分。

3.Math.round()

Math.round方法用于四舍五入

Math.round(0.1) // 0
Math.round(0.5) // 1
Math.round(0.6) // 1

// 等同于
Math.floor(x + 0.5)复制代码

4.Math.random()

Math.random方法返回0-1之间的一个随机数,可能等于0,但一定小于1


转载于:https://juejin.im/post/5a965c35f265da4e7b44db96

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值