JavaScript单例内置对象之Math

Math对象

ECMA提供了Math对象作为保存数学公式、信息、计算的地方。Math对象提供了一些计算的属性和方法。
注意:Math对象上提供的计算要比直接使用js实现快得多,这是因为Math对象上的计算使用了JS引擎中更高效的实现和处理器指令。
1. Math对象 属性
在这里插入图片描述
2. max() 和 min()方法

let max = Math.max(3, 54, 32, 16);
console.log(max); // 54
let min = Math.min(3, 54, 32, 16);
console.log(min); // 3 

// 使用扩展操作符
let values = [1, 2, 3, 4, 5, 6, 7, 8];
let max = Math.max(...val); 

3. 舍入方法

  • 把小数值舍入为整数,4个方法:Math.ceil()、Math.floor()、Math.round()、Math.fround()
    Math.ceil():向上舍入
    Math.floor():向下舍入
    Math.round():四舍五入
    Math.fround():返回数值最接近的单精度(32位)浮点值表示

4. random()方法
Math.random()始终返回小数
公式: number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)
eg:
1、打印1~10的整数:

console.log(Math.floor(Math.random()*10 + 1))
/*
这个例子中,1~10总共10个数,所以可选总数 total_number_of_choices为 10,最小可能值 first_possible_value为 1
*/

2、通过函数算出可选总数和最小可能值

function func(lowerValue, upperValue) {
    let choice = upperValue - lowerValue + 1;  //最大值减最小值加1为可选总数
    return Math.floor(Math.random()*choice + lowerValue);
}
func(2, 9);  //输出2-9的随机数

5.其它常见方法
x的power次幂:Math.pow(x, power) eg:Math.pow(2, 4)=16
平方根: Math.sqrt(x)
立方根:Math.cbrt(x)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值