JavaScript 学习笔记
1. 日期格式化 (Moment.js)
概念:Moment.js 是一个强大的库,用于格式化、操作和展示时间和日期,特别适合多种日期格式和时区处理。
用途:可以将复杂的日期操作简化,例如将时间转换成自定义格式,或者进行日期间的计算。
基础用法:格式化当前日期为 'YYYY-MM-DD' 格式。
const formattedDate = moment().format('YYYY-MM-DD');
console.log(`当前日期:${formattedDate}`);
进阶用法:显示当前日期的前一周的日期。
const oneWeekAgo = moment().subtract(7, 'days').format('YYYY-MM-DD');
console.log(`一周前的日期:${oneWeekAgo}`);
2. HTTP 请求 (Axios)
概念:Axios 是一个基于 Promise 的 HTTP 库,适用于浏览器和 Node.js,帮助简化 AJAX 请求的发送和响应处理。
用途:可以用来与服务器通信,例如发送数据或获取数据。
基础用法:发送一个简单的 GET 请求。
async function fetchData(url) {
try {
const response = await axios.get(url);
console.log('数据:', response.data);
} catch (error) {
console.error('请求出错:', error);
}
}
fetchData('https://jsonplaceholder.typicode.com/posts');
进阶用法:发送 POST 请求并附带请求体数据。
async function postData(url, data) {
try {
const response = await axios.post(url, data);
console.log('响应数据:', response.data);
} catch (error) {
console.error('请求出错:', error);
}
}
postData('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
});
3. 数组去重 (Lodash)
概念:Lodash 是一个实用工具库,提供了多种函数,帮助简化数据操作和集合处理。
用途:简化数组和对象的处理,特别是去重、筛选等操作。
基础用法:去重一个数组。
const numbers = [1, 2, 2, 3, 4, 5, 5];
const uniqueNumbers = _.uniq(numbers);
console.log('去重后的数组:', uniqueNumbers);
进阶用法:对对象数组去重(例如根据用户的 id 去重)。
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice' }
];
const uniqueUsers = _.uniqBy(users, 'id');
console.log('去重后的用户数组:', uniqueUsers);
4. Cookie 操作
概念:Cookie 是一种在浏览器中存储小量数据的方式,通常用于保存用户状态和偏好。
用途:存储用户信息、偏好或状态,例如保存登录状态。
基础用法:设置和读取 Cookie。
document.cookie = "username=John Doe";
function getCookie(name) {
const cookieArray = document.cookie.split('; ');
for (let cookie of cookieArray) {
const [key, value] = cookie.split('=');
if (key === name) return value;
}
return null;
}
console.log('Cookie:', getCookie('username'));
进阶用法:设置 Cookie 的过期时间。
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
setCookie('username', 'John Doe', 7); // 设置 7 天后过期
5. 存储 API
概念:存储 API 包括 localStorage 和 sessionStorage,用于在浏览器中存储数据。
用途:在浏览器中存储数据,支持持久性(localStorage)或临时存储(sessionStorage)。
基础用法:使用 localStorage 存储和读取数据。
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
console.log('主题:', theme);
进阶用法:删除 localStorage 中的数据并检查数据是否存在。
localStorage.removeItem('theme');
const theme = localStorage.getItem('theme') || 'default';
console.log('当前主题:', theme);