🧮 JS Math对象常用讲解

0 阅读1分钟

🧮 JS Math 对象 完全讲解

什么是 Math?

  • 内置对象,直接用不需要 new
  • 专门处理数字计算:取整、随机数、最大最小值、绝对值、乘方等
  • 所有方法都是直接调用:Math.xxx()

常用方法

Math.random () —— 生成随机数

作用:生成 0 ~ 1 之间的随机小数(包含 0,不包含 1)

Math.random(); // 0.12345  0.98765 等
Math.floor(Math.random() * 10) + 1; // 生成 1~10 的随机整数

// 生成 10 ~ 20 之间的随机整数
function rand(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Math.round (num) —— 四舍五入

Math.round(2.3); // 2
Math.round(2.6); // 3

// 保留两位小数
let price = 19.98765;
price = Math.round(price * 100) / 100; // 19.99

Math.ceil (num) —— 向上取整

作用:不管小数多少,都往大了取

Math.ceil(2.1); // 3
Math.ceil(2.9); // 3

Math.floor (num) —— 向下取整

作用:只保留整数,直接砍掉小数

Math.floor(2.9); // 2
Math.floor(2.1); // 2

Math.abs (num) —— 取绝对值

Math.abs(-5); // 5
Math.abs(5);  // 5

Math.max (...) —— 取最大值

Math.max(1, 3, 5, 2); // 5

Math.min (...) —— 取最小值

Math.min(1, 3, 5, 2); // 1

Math.pow (base, exp) —— 乘方

Math.pow(2, 3); // 2³ = 8

Math.sqrt (num) —— 开平方

Math.sqrt(9); // 3

Math.PI —— 圆周率常量

Math.PI; // 3.14159...