← 返回目录

15. Math 与 Date 内置对象

Math 是数学工具对象(取整、随机、最大最小),Date 是日期对象(拿当前时间、格式化)。

核心方法:
Math.random()——0~1 随机数
Math.floor() / Math.ceil() / Math.round()——向下/向上/四舍五入取整
new Date()——当前时间
getFullYear() / getMonth() / getDate()——取年月日

坑:getMonth() 从 0 开始(0=1月)、随机数要乘范围再取整、Date 月份要 +1

15.1 互动演示(取整对比 / 随机整数 / 当前时间)

点按钮看取整差异、toFixed 的字符串坑、以及 getMonth 为什么要 +1。

15.2 知识点逐条讲解(配合代码)

① Math 是工具箱,直接拿出来用

方法干嘛的例子
Math.floor往下取整(扔小数)floor(5.6)=5
Math.ceil往上取整(多1)ceil(5.1)=6
Math.round四舍五入round(5.5)=6
Math.random0到1之间随机小数含0不含1
Math.max/min一堆数里最大/最小max(1,9,3)=9

toFixed 坑:吐出来的是字符串!

如果你把 toFixed 的结果接着做加法,就会变成字符串拼接。因为 num.toFixed(2) 虽然看着像数字,其实是字符串。要继续算数得先 Number() 转一下。

let num = 3.14159;

// 保留两位 → "3.14",但吐出来的是字符串
num.toFixed(2);

③ 封装「[min, max] 随机整数」(两头都能取到)

// random出0~1小数,乘个数,再向下取整,最后加起始
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
// max-min+1 是关键:让最大最小都有机会被抽到
}

④ Date:月份从 0 开始,别忘了 +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();

⑥ X.3 实战:用在哪 / 常见坑 / 怎么解决

① 用在哪:抽奖随机数、倒计时取当前时间、金额保留两位小数、时间戳做排序。

② 常见坑:toFixed() 结果当数字用拼出字符串;getMonth() 忘了 +1 月份少 1。

③ 怎么解决:toFixedNumber() 转一下;月份一律 getMonth()+1;随机数套公式 floor(random*(max-min+1))+min

一句话记住:Math 不用 new 直接用;toFixed 返回字符串要转;随机整数用 floor(random*(max-min+1))+min;getMonth 要 +1;时间戳三种写法挑一个用

本页重点

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 开始要 +10~11
now.getMonth();  // 0-11
Date.now()时间戳毫秒数数字
Date.now();  // 毫秒数