JavaScript Math 与 Date 内置对象
JavaScript 自带一批现成的对象,提供常用功能,不用自己从头实现。这一节讲最常用的两个,Math 和 Date。一个做数学计算,一个处理日期时间。
Math 对象
Math 提供数学相关的常量和计算方法。它不需要 new,直接用 Math.方法名() 调用。
取整系列
Math.floor() 向下取整,Math.ceil() 向上取整,Math.round() 四舍五入。
console.log(Math.floor(3.7));
console.log(Math.ceil(3.2));
console.log(Math.round(3.5));
依次输出 3、4、4。floor 不管小数多大都往下取,ceil 不管多小都往上取,round 按四舍五入走。
负数时取整方向要注意。Math.floor(-3.2) 的结果是 -4,Math.round(-3.2) 是 -3,方向不同。用到负数时先验证一下结果。
随机数
Math.random() 返回 0 到 1 之间的随机数,包含 0,不包含 1。每次调用结果都不一样。
console.log(Math.random());
console.log(Math.random());
两次输出都是 0 和 1 之间的小数,具体值每次运行都不同。
最大值和最小值
Math.max() 和 Math.min() 从传入的参数里找出最大和最小值。
console.log(Math.max(3, 8, 5));
console.log(Math.min(3, 8, 5));
依次输出 8、3。
随机整数技巧
随机数的常见用法是生成随机整数,比如抽奖、随机出题。技巧是 Math.floor(Math.random() * 最大值),生成 0 到 最大值减 1 的整数。原因是随机数最大不到 1,乘以后最大不到最大值,向下取整就到不了最大值本身。
console.log(Math.floor(Math.random() * 10));
每次输出 0 到 9 的整数。想要 1 到 n,结果加 1 就行。
console.log(Math.floor(Math.random() * 6) + 1);
模拟掷骰子,输出 1 到 6 的整数。
Date 对象
Date 处理日期和时间。和 Math 不同,创建日期实例要用 new Date()。
const now = new Date();
console.log(now);
输出当前日期时间。括号里传三个数字可以指定日期,表示年月日。注意月份从 0 开始,0 代表一月,1 代表二月,依此类推。
const d = new Date(2026, 0, 1);
console.log(d);
输出 2026 年 1 月 1 日。把 0 写成 1,得到的就是 2 月 1 日,这个坑要记住。
读取日期的各部分
创建好日期后,用一组 get 方法读取各个部分。
const now = new Date();
console.log(now.getFullYear());
console.log(now.getMonth());
console.log(now.getDate());
console.log(now.getHours());
console.log(now.getMinutes());
console.log(now.getSeconds());
依次输出当前年份、月份、日、时、分、秒。getMonth() 同样从 0 开始,输出 0 到 11,想显示成 1 到 12 要加 1。
把各部分拼起来,就能得到当前时间的字符串,做页面时间显示很常用。
const now = new Date();
const text = now.getFullYear() + '年' + (now.getMonth() + 1) + '月' + now.getDate() + '日';
console.log(text);
输出类似 2026年8月21日。单数字时显示会像 2026年8月7日,想补零可以用后面学的字符串方法处理。
小结
Math 用 Math.方法名() 直接调用,包括 floor、ceil、round、max、min 和 random。Math.floor(Math.random() * 最大值) 生成 0 到 最大值减 1 的整数,加 1 就变成 1 到最大值。Date 用 new Date() 创建实例,getFullYear、getMonth、getDate 等方法读取各部分,月份从 0 开始,使用时记得加 1。