下面是JavaScript 开发中非常有用、但很多人没系统总结过的技巧按「日常高频 + 进阶 + 工程化」分层讲,基本都是能立刻提升代码质量和效率的,并且偏实战。
一、日常开发必会的实用技巧(高频)
1️⃣ 可选链 + 空值合并(避免大量 if)
const city = user?.profile?.address?.city ?? '未知'✅ 比&&清晰
✅ 防止Cannot read property of undefined
2️⃣ 解构 + 默认值(写代码更短)
function createUser({ name, age = 18 } = {}) { console.log(name, age) }👉参数解构 + 默认值是函数设计的神器
3️⃣ 一行数组去重
const unique = [...new Set(arr)]4️⃣ 快速判断空数组 / 空对象
if (!arr?.length) {} if (!Object.keys(obj).length) {}5️⃣ 安全的 JSON 解析
function safeJSONParse(str, defaultValue = null) { try { return JSON.parse(str) } catch { return defaultValue } }在接口返回不稳定时非常有用
二、函数 & 代码组织技巧(写得更优雅)
6️⃣ 函数参数用对象,而不是多个参数
❌ 不推荐:
createOrder(id, price, count, coupon, remark)✅ 推荐:
createOrder({ id, price, count, coupon, remark })📌 好处:
可读性强
参数顺序无所谓
易扩展
7️⃣ 提前 return,减少嵌套
❌
if (isLogin) { if (isVip) { doSomething() } }✅
if (!isLogin) return if (!isVip) return doSomething()8️⃣ 善用 map / filter / reduce
const total = orders .filter(o => o.paid) .reduce((sum, o) => sum + o.price, 0)📌 比 for 循环更表达「业务意图」
9️⃣ 默认使用const
const list = [] list.push(1) // OK👉能用 const 就不用 let
三、异步 & Promise 的关键技巧(非常重要)
🔟 Promise.all + Promise.allSettled
await Promise.all([fetchUser(), fetchOrder()]) const results = await Promise.allSettled(tasks)📌
all:有一个失败就失败allSettled:适合「部分成功」场景(如批量请求)
1️⃣1️⃣ async/await + try/catch
try { const data = await fetchData() } catch (err) { console.error(err) }❗ 不要滥用.then().catch()
1️⃣2️⃣ 超时 Promise 封装
function withTimeout(promise, ms = 5000) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms) ) ]) }四、性能 & 体验优化技巧
1️⃣3️⃣ 防抖 & 节流(必会)
function debounce(fn, delay) { let timer return (...args) => { clearTimeout(timer) timer = setTimeout(() => fn(...args), delay) } }👉 搜索、输入框、resize 必用
1️⃣4️⃣ 懒加载(图片 / 模块)
const module = await import('./heavy.js')<img loading="lazy" src="xx.jpg" />1️⃣5️⃣ 避免重复计算(缓存)
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 }五、工程化 & 可维护性技巧(拉开差距)
1️⃣6️⃣ 不要直接修改参数
❌
function update(obj) { obj.name = 'x' }✅
function update(obj) { return { ...obj, name: 'x' } }📌 对 React / Vue 非常重要
1️⃣7️⃣ 常量集中管理
export const STATUS = { SUCCESS: 1, FAIL: 0 }❌ 避免魔法数字
1️⃣8️⃣ 善用短路逻辑
isDev && console.log('debug') callback && callback()1️⃣9️⃣ 使用 JSDoc(即使不用 TS)
/** * @param {number} price * @param {number} count * @returns {number} */ function calc(price, count) { return price * count }📌 编辑器能直接提示类型
六、一条高级建议(很多人忽略)
好 JS 代码 = “一眼就知道在干嘛”
判断标准:
变量名是否在表达业务?
是否减少了嵌套?
是否避免了副作用?
是否方便未来改?