JavaScript加强篇——第四章 日期对象与DOM节点(基础)
目录
一、DOM节点基础
二、日期对象实例化
三、日期对象方法
四、时间戳与应用
本文摘要:文章系统介绍了Web开发中的DOM节点和JavaScript日期对象两大核心知识点。DOM部分讲解了四种节点类型(元素、属性、文本及其他)及其树形结构特性。日期对象部分详细说明:1)三种实例化方式;2)常用方法(需注意月份需+1);3)时间戳的三种获取方式及应用场景。特别强调实际开发中的注意事项,如月份计数规则、时间差计算的最佳实践,并提供了倒计时案例和面试常见问题解答。全文采用"节点四类型,日期三要点"口诀帮助记忆核心概念。
一、DOM节点基础
节点类型
节点类型 | 说明 | 示例 |
---|---|---|
元素节点 | HTML标签 | <div> , <p> |
属性节点 | 标签属性 | href , id , class |
文本节点 | 标签内的文本内容 | "Hello World" |
其他节点 | 注释/文档声明等 | <!-- comment --> |
DOM树结构示例
⚠️ 关键特性
-
整个DOM文档是一个节点树
-
html
是根节点 -
元素节点可以包含子节点(文本/元素/属性节点)
-
属性节点不是元素节点的子节点,而是其属性
二、日期对象实例化
创建日期对象
// 1. 获取当前时间
const now = new Date();
console.log(now); // 输出: Sat Jun 01 2024 14:30:00 GMT+0800// 2. 获取指定时间
const olympics = new Date('2028-08-08');
console.log(olympics); // 输出: Tue Aug 08 2028 00:00:00 GMT+0800// 3. 使用年月日参数
const birthday = new Date(1995, 10, 20); // 月份从0开始计数!
console.log(birthday); // 输出: Mon Nov 20 1995 00:00:00
❗ 重要注意事项
月份参数从0开始计数:
0 = 一月
1 = 二月
...
11 = 十二月
三、日期对象方法
常用方法
方法 | 返回值范围 | 说明 |
---|---|---|
getFullYear() | 四位数年份 | 如 2024 |
getMonth() | 0-11 | 0=一月,11=十二月 |
getDate() | 1-31 | 每月中的第几天 |
getDay() | 0-6 | 0=周日,1=周一,6=周六 |
getHours() | 0-23 | 24小时制 |
getMinutes() | 0-59 | 分钟数 |
getSeconds() | 0-59 | 秒数 |
格式化日期示例
function formatDate(date) {const days = ['日', '一', '二', '三', '四', '五', '六'];return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 星期${days[date.getDay()]}`;
}const today = new Date();
console.log(formatDate(today)); // 输出: 2024年6月1日 星期六
⚠️ 易错点提醒
const date = new Date();// 错误:忘记月份需要+1
console.log(`错误: ${date.getMonth()}月`); // 输出: 5月(实际是6月)// 正确:月份+1
console.log(`正确: ${date.getMonth() + 1}月`); // 输出: 6月
四、时间戳与应用
时间戳概念
从1970年1月1日00:00:00 UTC起经过的毫秒数
用于精确计算时间间隔
三种获取方式
// 1. getTime()方法
const time1 = new Date().getTime();// 2. +new Date()(推荐)
const time2 = +new Date(); // 3. Date.now()(仅当前时间)
const time3 = Date.now();console.log(time1, time2, time3); // 输出三个相同的时间戳
倒计时应用
// 计算距离年底的倒计时
function countdown() {// 1. 获取当前时间戳const now = +new Date();// 2. 获取年底时间戳const end = +new Date('2024-12-31 23:59:59');// 3. 计算剩余毫秒数const remaining = end - now;// 4. 转换为天/时/分/秒const days = Math.floor(remaining / (1000 * 60 * 60 * 24));const hours = Math.floor(remaining % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));const mins = Math.floor(remaining % (1000 * 60 * 60) / (1000 * 60));const secs = Math.floor(remaining % (1000 * 60) / 1000);return `${days}天 ${hours}时 ${mins}分 ${secs}秒`;
}// 每秒更新
setInterval(() => {console.log(countdown());
}, 1000);
⭐ 最佳实践
-
时间计算统一使用时间戳
-
优先使用
+new Date()
获取时间戳 -
倒计时结束时清除定时器:
if(remaining <= 0) {clearInterval(timer);console.log('倒计时结束!');
}
✅ 核心要点总结
📝 高频面试题速答
-
Q:DOM中有哪些节点类型?
A:元素节点、属性节点、文本节点、其他节点(注释等)
-
Q:如何创建表示"2025年圣诞节"的日期对象?
A:
new Date(2025, 11, 25)
(注意月份11表示十二月) -
Q:获取时间戳的三种方式?
A:
getTime()
、+new Date()
、Date.now()
-
Q:为什么日期对象的getMonth()需要+1?
A:因为月份从0开始计数(0=一月,11=十二月)
-
Q:如何计算两个日期的时间差?
A:转换为时间戳后相减:
+new Date(end) - +new Date(start)
🧠 记忆口诀
"节点四类型,日期三要点"
四类型:元素、属性、文本、其他
三要点:实例化、方法、时间戳