JavaScript 技巧
ES6+ 常用语法
javascript
// 解构赋值
const { name, age = 18 } = user
const [first, ...rest] = array
// 可选链操作符(避免 undefined 报错)
const city = user?.address?.city ?? '未知'
// 空值合并
const value = input ?? 'default'异步处理
javascript
// async/await(推荐)
async function fetchData(url) {
try {
const res = await fetch(url)
const data = await res.json()
return data
} catch (err) {
console.error('请求失败:', err)
}
}
// Promise.all 并发请求
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
])数组常用方法
javascript
const arr = [1, 2, 3, 4, 5]
arr.map(x => x * 2) // [2,4,6,8,10]
arr.filter(x => x > 2) // [3,4,5]
arr.reduce((acc, x) => acc + x, 0) // 15
arr.find(x => x > 3) // 4
arr.some(x => x > 4) // true
arr.every(x => x > 0) // true
arr.flat() // 扁平化嵌套数组