第17章 附录:ES6 速查

第 17 节 / 共 17 节 课程:前后端穿透

现代前端代码大量使用 ES6+ 语法。你不需要背全部,但下面这些必须能读懂。读不懂时,回到这里查。

17.1 let 与 const

用 let 声明会变的变量,用 const 声明不重新赋值的变量。const 不等于“值不可变”,对象的属性仍可改。

let count = 0
count = count + 1
 
const user = { name: 'Tom' }
user.name = 'Jerry' // 可以
// user = {} // 报错

不要再用 var。它有变量提升和函数作用域,容易出 bug。

17.2 箭头函数

const add = (a, b) => a + b
const square = n => n * n
const load = async () => {
    const res = await fetch('/api/courses')
    return res.json()
}

箭头函数没有自己的 this,适合回调和短函数。对象方法、需要动态 this 的场景不要用箭头函数。

17.3 模板字符串

用反引号包裹,可以换行;插值写成美元符号加花括号包住变量名,例如 ${user}。反引号在键盘左上角,和波浪号同一个键。

const user = 'Vue'
const msg = `hello ${user}`

拼接字符串容易漏空格、漏引号;模板字符串更直观。但不要在模板字符串里塞复杂表达式,先算好变量。

17.4 解构

const user = { id: 1, name: 'Tom', role: 'admin' }
const { id, name } = user
 
const list = [10, 20, 30]
const [first, second] = list
 
function show({ name, role = 'user' }) {
    console.log(name, role)
}

解构可以设默认值,也可以重命名:const { name: userName } = user。

17.5 展开与剩余

const a = [1, 2]
const b = [...a, 3, 4]
 
const user = { name: 'Tom', age: 18 }
const next = { ...user, age: 19 }
 
function sum(...nums) {
    return nums.reduce((s, n) => s + n, 0)
}

展开是浅拷贝。嵌套对象仍共享引用,需要深拷贝时用 structuredClone 或专门库。

17.6 模块

// math.js
export function add(a, b) { return a + b }
export const PI = 3.14
 
// main.js
import { add, PI } from './math.js'
import * as math from './math.js'

一个文件一个模块。默认导出用 export default,导入时名字可自取;命名导出必须用花括号,名字要一致。

17.7 Promise 与 async/await

async function load() {
    try {
        const res = await fetch('/api/courses')
        if (!res.ok) throw new Error('HTTP ' + res.status)
            const data = await res.json()
            return data } catch (e) {
            console.error(e)
            throw e
    }
}

await 只能放在 async 函数里。多个互不依赖的请求可以 Promise.all 并行,不要一条条串行等。

const [courses, user] = await Promise.all([
fetch('/api/courses').then(r => r.json()),
fetch('/api/me').then(r => r.json())
])

17.8 可选链与空值合并

const name = user?.profile?.name ?? '匿名'
const len = list?.length ?? 0

?. 遇到 null/undefined 就短路,不报错;?? 只在 null/undefined 时取默认值,不会把 0 和空字符串误判。

17.9 数组常用方法

方法作用是否改原数组
map每个元素变换,返回新数组否
filter按条件筛选否
find找第一个匹配否
some / every是否存在/是否全部否
reduce累计成一个值否
sort排序是(会改原数组)
forEach遍历,无返回值否
const names = courses
.filter(c => c.valid === '1')
.sort((a, b) => a.sortNo - b.sortNo)
.map(c => c.name)

注意 sort 会修改原数组。不想改就先 [...list].sort()。数字排序要传比较函数,否则按字符串排,10 会排在 2 前面。

17.10 类与 this

class Course {
    constructor(name) {
        this.name = name
    }
 
    intro() {
        return '课程:' + this.name
    }
}
 
const c = new Course('前后端穿透')
console.log(c.intro())

Vue 3 的选项式 API 里,this 指向组件实例;组合式 API 里通常不需要 this。混用时要特别小心。

17.11 速查表

语法用途
let / const变量声明
=>箭头函数
反引号模板字符串
...展开/剩余
{ a, b } = obj解构
import / export模块
async / await异步
?. / ??安全访问与默认值
map / filter / reduce数组变换

到这里,课程正文结束。真正的提升来自做项目:把第 15 章的四个迭代做完,再回头读第 14 章部署,你会理解每一行配置为什么存在。