如何永久保存微信聊天记录:从数据提取到年度报告生成完整指南
2026/6/21 16:23:46
下面是JavaScript 开发中非常有用、但很多人没系统总结过的技巧按「日常高频 + 进阶 + 工程化」分层讲,基本都是能立刻提升代码质量和效率的,并且偏实战。
const city = user?.profile?.address?.city ?? '未知'✅ 比&&清晰
✅ 防止Cannot read property of undefined
function createUser({ name, age = 18 } = {}) { console.log(name, age) }👉参数解构 + 默认值是函数设计的神器
const unique = [...new Set(arr)]if (!arr?.length) {} if (!Object.keys(obj).length) {}function safeJSONParse(str, defaultValue = null) { try { return JSON.parse(str) } catch { return defaultValue } }在接口返回不稳定时非常有用
❌ 不推荐:
createOrder(id, price, count, coupon, remark)✅ 推荐:
createOrder({ id, price, count, coupon, remark })📌 好处:
可读性强
参数顺序无所谓
易扩展
❌
if (isLogin) { if (isVip) { doSomething() } }✅
if (!isLogin) return if (!isVip) return doSomething()const total = orders .filter(o => o.paid) .reduce((sum, o) => sum + o.price, 0)📌 比 for 循环更表达「业务意图」
constconst list = [] list.push(1) // OK👉能用 const 就不用 let
await Promise.all([fetchUser(), fetchOrder()]) const results = await Promise.allSettled(tasks)📌
all:有一个失败就失败
allSettled:适合「部分成功」场景(如批量请求)
try { const data = await fetchData() } catch (err) { console.error(err) }❗ 不要滥用.then().catch()
function withTimeout(promise, ms = 5000) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms) ) ]) }function debounce(fn, delay) { let timer return (...args) => { clearTimeout(timer) timer = setTimeout(() => fn(...args), delay) } }👉 搜索、输入框、resize 必用
const module = await import('./heavy.js')<img loading="lazy" src="xx.jpg" />const cache = new Map() function fib(n) { if (cache.has(n)) return cache.get(n) const result = n <= 1 ? n : fib(n-1) + fib(n-2) cache.set(n, result) return result }❌
function update(obj) { obj.name = 'x' }✅
function update(obj) { return { ...obj, name: 'x' } }📌 对 React / Vue 非常重要
export const STATUS = { SUCCESS: 1, FAIL: 0 }❌ 避免魔法数字
isDev && console.log('debug') callback && callback()/** * @param {number} price * @param {number} count * @returns {number} */ function calc(price, count) { return price * count }📌 编辑器能直接提示类型
好 JS 代码 = “一眼就知道在干嘛”
判断标准:
变量名是否在表达业务?
是否减少了嵌套?
是否避免了副作用?
是否方便未来改?