Math 是数学工具对象(取整、随机、最大最小),Date 是日期对象(拿当前时间、格式化)。
核心方法:
① Math.random()——0~1 随机数
② Math.floor() / Math.ceil() / Math.round()——向下/向上/四舍五入取整
③ new Date()——当前时间
④ getFullYear() / getMonth() / getDate()——取年月日
坑:getMonth() 从 0 开始(0=1月)、随机数要乘范围再取整、Date 月份要 +1。
| 方法 | 干嘛的 | 例子 |
|---|---|---|
| Math.floor | 往下取整(扔小数) | floor(5.6)=5 |
| Math.ceil | 往上取整(多1) | ceil(5.1)=6 |
| Math.round | 四舍五入 | round(5.5)=6 |
| Math.random | 0到1之间随机小数 | 含0不含1 |
| Math.max/min | 一堆数里最大/最小 | max(1,9,3)=9 |
如果你把 toFixed 的结果接着做加法,就会变成字符串拼接。因为 num.toFixed(2) 虽然看着像数字,其实是字符串。要继续算数得先 Number() 转一下。
let num = 3.14159; // 保留两位 → "3.14",但吐出来的是字符串 num.toFixed(2);
// random出0~1小数,乘个数,再向下取整,最后加起始
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
// max-min+1 是关键:让最大最小都有机会被抽到
}
// 新建一个"现在"的时间对象 let time = new Date(); // 年 time.getFullYear(); // 月是0~11,必须+1才是真实月 time.getMonth() + 1; // 几号 time.getDate(); // 星期(周日0~周六6) time.getDay();
如果你直接打印 getMonth(),就会比真实月份少 1。因为它返回 0~11(0就是1月)。这是新手必踩坑,取月一律 +1。
// 写法1:拿时间戳 new Date().getTime(); + // 写法2:加号简写 new Date(); // 写法3:最推荐 Date.now();
① 用在哪:抽奖随机数、倒计时取当前时间、金额保留两位小数、时间戳做排序。
② 常见坑:toFixed() 结果当数字用拼出字符串;getMonth() 忘了 +1 月份少 1。
③ 怎么解决:toFixed 后 Number() 转一下;月份一律 getMonth()+1;随机数套公式 floor(random*(max-min+1))+min。
| API | 作用 | 参数 | 返回值 | 代码示例 |
|---|---|---|---|---|
| Math.round(x) | 四舍五入 | 数字 | 整数 | Math.round(4.5); // 5 |
| Math.floor(x) | 向下取整 | 数字 | 整数 | Math.floor(4.9); // 4 |
| x.toFixed(n) | 保留 n 位小数(返回字符串) | 位数 | 字符串 | (3.1415).toFixed(2); // "3.14" |
| new Date() | 拿到当前时间 | 无 | 日期对象 | let now = new Date(); |
| date.getMonth() | 月份,从 0 开始要 +1 | 无 | 0~11 | now.getMonth(); // 0-11 |
| Date.now() | 时间戳毫秒数 | 无 | 数字 | Date.now(); // 毫秒数 |