指南

Math 和 Date 用法详解

通过实用示例深入理解 JavaScript 中 Math 和 Date 对象的常见用法,适合前端初学者快速掌握。

🎯 引言

学会 Math 数学对象,你就可以利用 JavaScript 实现数学计算,比如取整、随机数生成等常见功能,利用 Date 日期对象获取日期时间,并且对齐进行日期格式化。


🔢 Math 对象基础与实用示例

JavaScript 中的 Math 对象是一个内置的数学工具箱,里面包含各种数学常量和函数。对于刚入门前端的朋友来说,掌握 Math 是非常重要的,比如我们经常需要对数字进行取整、求最小值、最大值或者生成随机数。

常用 Math 方法介绍

  • Math.round(x):对数字四舍五入。
  • Math.floor(x):向下取整,比如 2.9 -> 2。
  • Math.ceil(x):向上取整,比如 2.1 -> 3。
  • Math.random():生成 0(包含)到 1(不包含)之间的随机小数。
  • Math.max(a, b, c, ...)Math.min(a, b, c, ...):求最大值和最小值。
Math.random() 生成的随机数是伪随机的,每次页面刷新会不同,适合简单的随机效果。

例子 1:生成 1 到 100 之间的随机整数

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>

<div class="example" id="randomNumber"></div>

<script>
    function getRandomInt(min, max) {
        // Math.random() 生成0到1随机小数,乘以区间大小,再加上最小值,最后向下取整
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    document.getElementById('randomNumber').textContent =
        '随机数(1~100):' + getRandomInt(1, 100);
</script>

这里 getRandomInt 函数可以灵活生成任意区间的整数,前端游戏、抽奖、分页等项目很常见。

例子 2:计算数组中的最大值和最小值

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="maxMin"></div>

<script>
    const numbers = [10, 23, 45, 2, 78, 34];
    const max = Math.max(...numbers);
    const min = Math.min(...numbers);

    document.getElementById('maxMin').textContent = `数组最大值是 ${max},最小值是 ${min}`;
</script>

这里临时用到了 ES6 扩展运算符 ...,把数组展开成参数列表传给 Math.maxMath.min


⏰ Date 对象基础与实操

Date 对象是 JavaScript 用来处理日期和时间的工具。日常项目中经常会用到,比如显示当前时间、计算时间差、格式化日期等。

创建 Date 对象

  • new Date():创建当前时间的日期对象。
  • new Date('2024-06-01'):传入日期字符串创建指定日期对象。
  • new Date(timestamp):用时间戳创建时间对象。

获取 Date 对象的方法

  • getFullYear():获取四位年份。
  • getMonth():获取月份(0~11,0代表1月)。
  • getDate():获取一个月中的第几天。
  • getHours(), getMinutes(), getSeconds():获取时分秒。
注意 Date 的月份是从 0 开始的,所以要加 1 显示正常月份。

例子 3:显示当前格式化时间 YYYY-MM-DD HH:mm:ss

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="currentTime"></div>

<script>
    function formatDate(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        // 补零函数,个位数补0
        const padZero = num => (num < 10 ? '0' + num : num);

        return (
            `${year}-${padZero(month)}-${padZero(day)} ` +
            `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`
        );
    }

    const now = new Date();
    document.getElementById('currentTime').textContent = '当前时间:' + formatDate(now);
</script>

例子 4:计算两个日期之间的天数差

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="dateDiff"></div>

<script>
    const date1 = new Date('2024-06-01');
    const date2 = new Date('2024-06-10');

    // 计算时间差,单位是毫秒
    const diffTime = date2.getTime() - date1.getTime();
    // 1 天 = 24 * 60 * 60 * 1000 毫秒
    const diffDays = diffTime / (1000 * 60 * 60 * 24);

    document.getElementById('dateDiff').textContent = `日期相差 ${diffDays}`;
</script>

🧾 小节总结

  • Math 是前端中处理数字计算的利器,熟练掌握常用函数能简化很多工作。
  • Date 用来处理时间相关问题,注意月份从 0 开始,时间差计算要用毫秒。
  • 结合实际场景练习,比如随机数用于抽奖,Date 用于倒计时和时间显示。

❓ 知识问答(Q&A)

Q:Math.random() 生成的随机数包括 1 吗?
A:不包括,随机数范围是 0(包含)到 1(不包含)。

Q:Date 对象的月份为什么要加 1?
A:JavaScript 中月份是从 0 开始编号的,0 表示 1 月,所以显示时需要加 1。

Q:如何判断两个日期相差多少天?
A:先用 getTime() 获取时间戳,计算差值后除以一天的毫秒数即可。


🧪 小练习

练习 1:使用 Math 实现一个随机颜色生成器(例如 #a1b2c3)

<style>
    .color-box {
        width: 100px;
        height: 100px;
        border: 1px solid #ccc;
        margin-top: 10px;
    }
</style>
<div>
    <button id="colorBtn">生成随机颜色</button>
    <div class="color-box" id="colorBox"></div>
</div>

<script>
    // 请完成下面的函数,点击按钮时,生成一个随机十六进制颜色并应用到 colorBox 背景色上
    function getRandomColor() {
        // TODO: 实现随机颜色生成
    }

    document.getElementById('colorBtn').onclick = function () {
        const color = getRandomColor();
        document.getElementById('colorBox').style.backgroundColor = color;
    };
</script>

练习 2:用 Date 实现一个简单的倒计时,显示距离某个未来日期还剩多少天、小时、分钟

<div id="countdown"></div>

<script>
    // 请写一个函数,计算距离 2024-12-31 00:00:00 还有多少天、小时、分钟,并显示在 countdown 中
    function countdown() {
        // TODO: 实现倒计时功能
    }

    setInterval(countdown, 1000); // 每秒更新一次
</script>

🎉 恭喜你已经掌握 Math 的取整、随机数生成和 Date 的日期时间操作技能啦!这些基础内容,是你成为前端高手的必备武器。继续加油,实践让你更强!