Skip to content

当然可以兄弟,来来来,我这就给你一份 最全但不啰嗦的 Math 全家桶讲解,把属性 + 方法都讲清楚,通俗易懂 + 举例,帮你快速上手。


🧱 一、Math 属性(常量)——前面讲过,这里复习一下

属性名含义举例用途
Math.PI圆周率 π圆面积、弧度换算
Math.E自然常数 ee^x 之类计算
Math.LN2ln(2) 自然对数对数运算
Math.LN10ln(10)对数运算
Math.LOG2Elog₂(e)对数换底
Math.LOG10Elog₁₀(e)对数换底
Math.SQRT1_21 / √2几何计算
Math.SQRT2√2勾股定理、几何计算

🔧 二、Math 方法(重点!)

下面这些方法用得超频,尤其是在前端页面、交互、动画、游戏中。


🎲 1. 随机数

方法说明示例
Math.random()返回 0 到 1 之间的随机数(不含1)Math.random() 👉 0.325...
👉 自定义范围随机数Math.floor(Math.random() * (max - min + 1)) + min
js
// 生成 1 到 10 的随机整数
let rand = Math.floor(Math.random() * 10) + 1;

🔢 2. 取整/四舍五入系列

方法说明示例
Math.floor(x)向下取整(地板)Math.floor(4.7) 👉 4
Math.ceil(x)向上取整(天花板)Math.ceil(4.1) 👉 5
Math.round(x)四舍五入Math.round(4.5) 👉 5
Math.trunc(x)直接去掉小数部分(不四舍五入)Math.trunc(4.9) 👉 4

➕➖ 3. 最大最小值

方法说明示例
Math.max(a, b, …)多个值中取最大Math.max(3, 8, 5) 👉 8
Math.min(a, b, …)多个值中取最小Math.min(3, 8, 5) 👉 3

🧮 4. 幂、根、绝对值

方法说明示例
Math.pow(x, y)幂运算 x 的 y 次方Math.pow(2, 3) 👉 8
Math.sqrt(x)平方根Math.sqrt(9) 👉 3
Math.cbrt(x)立方根Math.cbrt(27) 👉 3
Math.abs(x)绝对值Math.abs(-5) 👉 5

📐 5. 三角函数(单位是“弧度”)

方法说明
Math.sin(x)正弦
Math.cos(x)余弦
Math.tan(x)正切
Math.asin(x)反正弦
Math.acos(x)反余弦
Math.atan(x)反正切

🧠 弧度 = 角度 × π / 180

js
let angle = 30;
let radians = angle * Math.PI / 180;
console.log(Math.sin(radians)); // ≈ 0.5

🧭 6. 角度相关

方法说明
Math.atan2(y, x)给你 y 和 x,返回角度(常用于计算方向)
js
let angle = Math.atan2(1, 1); // 返回 45 度对应的弧度(≈ 0.785)

✅ 实战建议(常用组合)

场景方法搭配
随机整数Math.random() + Math.floor()
页面滚动条百分比Math.floor(滚动位置 / 总高度 * 100)
弹窗、拖拽边界判断Math.max() / Math.min() 控制范围
移动方向判断(2D游戏)Math.atan2()
缩放动画、旋转角度计算Math.sin() / Math.cos()

🧠 最后的记忆法则

  • 想随机:random
  • 想取整:floor / ceil / round
  • 想对比:max / min
  • 想做数学:pow / sqrt / abs
  • 想搞三角:sin / cos / atan2

兄弟你学完这套基本就能应对日常前端项目的各种数值计算了。
后面你要做动画、游戏、图形计算,这玩意都是基石。