目录
1.什么是Math对象
Math是一个内置对象,具有数学常数和函数的属性和方法。它不是一个函数对象。Math适用于Number类型,但是不适用BigInt。与许多其他全局对象不同,Math它不是构造函数,所以他不要单独创建。所有属性和方法Math都是静态的。您将常数 pi 称为Math.PI并将正弦函数称为Math.sin(x),其中x是方法的参数。常量是在 JavaScript 中以实数的完全精度定义的。
2.Math的常用方法
Math.ceil()
console.log(Math.ceil(.95));
// 输出: 1
console.log(Math.ceil(4));
// 输出: 4
console.log(Math.ceil(7.004));
// 输出: 8
console.log(Math.ceil(-7.004));
// 输出: -7
// 返回大于参数的最小整数
Math.floor()
console.log(Math.floor(5.95));
// 输出: 5
console.log(Math.floor(5.05));
// 输出: 5
console.log(Math.floor(5));
// 输出: 5
console.log(Math.floor(-5.05));
// 输出: -6
//该Math.floor()函数返回小于或等于给定数字的最大整数
Math.random()
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
console.log(getRandomInt(3));
// 输出: 0, 1 or 2
console.log(getRandomInt(1));
// 输出: 0
console.log(Math.random());
// 输出一个0-1之间的随机小数
//该Math.random()函数返回一个浮点伪随机数,范围为 0 到小于 1(包括 0,但不包括 1),在该范围内大致均匀分布——然后您可以将其缩放到所需的范围。实现选择随机数生成算法的初始种子;用户不能选择或重置它。
Math.round()
console.log(Math.round(0.9));
// 输出: 1
console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// 输出: 6 6 5
console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// 输出: -5 -5 -6
//该Math.round()函数返回四舍五入到最接近整数的数值