一、变量声明
javascript
// let 块级作用域变量
let count = 0
count = 1 // ✅ 可重新赋值
if (true) {
let count = 2 // ✅ 新的块级变量
}
// const 常量(引用不可变)
const PI = 3.14159
// PI = 3.14 // ❌ 报错
const user = { name: 'John' }
user.name = 'Jane' // ✅ 可修改属性
// user = {} // ❌ 不可重新赋值
二、箭头函数
javascript
// 语法:(参数) => 返回值
const add = (a, b) => a + b
// 相当于:
const add = function(a, b) {
return a + b
}
// this 绑定(无自己的this)
const person = {
name: 'John',
sayName: function() {
setTimeout(() => {
console.log(this.name) // ✅ 正确:John
}, 100)
}
}
三、模板字符串
javascript
const name = 'John'
const age = 25
// 插值
const msg = `姓名:${name},年龄:${age}`
// 多行
const html = `
<div>
<h1>${name}</h1>
</div>
`
// 表达式
const result = `${1 + 2} = ${add(1, 2)}`
四、解构赋值
javascript
// 数组解构
const [a, b, ...rest] = [1, 2, 3, 4]
// a=1, b=2, rest=[3,4]
// 对象解构
const { name, age } = { name: 'John', age: 25 }
const { name: userName } = { name: 'John' }
// userName='John'
// 函数参数解构
function print({ name, age }) {
console.log(`${name}, ${age}`)
}
五、函数增强
javascript
// 默认参数
function greet(name = 'Guest') {
return `Hello, ${name}`
}
// 剩余参数
function sum(...numbers) {
return numbers.reduce((a, b) => a + b)
}
sum(1, 2, 3) // 6
// 参数解构 + 默认值
function createUser({ name = 'Anon', age = 0 } = {}) {
return { name, age }
}
六、扩展运算符
javascript
// 数组展开
const arr1 = [1, 2]
const arr2 = [...arr1, 3, 4] // [1,2,3,4]
// 对象展开(浅拷贝)
const obj1 = { a: 1, b: 2 }
const obj2 = { ...obj1, c: 3 } // {a:1,b:2,c:3}
// 数组合并
const merged = [...arr1, ...arr2]
// 函数参数展开
Math.max(...[1, 2, 3]) // 相当于 Math.max(1,2,3)
七、对象简写
javascript
const name = 'John'
const age = 25
// 属性简写
const user = { name, age }
// 相当于 { name: name, age: age }
// 方法简写
const obj = {
sayHi() { // 代替 sayHi: function() {}
console.log('Hi')
}
}
// 计算属性名
const key = 'status'
const obj2 = {
[key]: 'active',
['get_' + key]() {
return this[key]
}
}
八、Class 类
javascript
// 定义类
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
// 方法
sayHi() {
return `Hi, I'm ${this.name}`
}
// Getter/Setter
get info() {
return `${this.name}, ${this.age}`
}
// 静态方法
static create(name) {
return new Person(name, 0)
}
}
// 继承
class Employee extends Person {
constructor(name, age, title) {
super(name, age) // 调用父类构造函数
this.title = title
}
}
const john = new Person('John', 25)
john.sayHi()
九、模块化
javascript
// module.js
export const PI = 3.14159
export function add(a, b) { return a + b }
export default class Calculator {}
// app.js
import Calculator, { PI, add } from './module.js'
import * as Module from './module.js'
// 动态导入
const module = await import('./module.js')
十、Promise 与 Async/Await
javascript
// Promise 基础
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
// Promise 组合
Promise.all([promise1, promise2]) // 全部成功
Promise.race([promise1, promise2]) // 最先完成
// Async/Await(同步写法)
async function getData() {
try {
const response = await fetch(url)
const data = await response.json()
return data
} catch (error) {
console.error(error)
}
}
十一、迭代器与生成器
javascript
// 迭代协议(可迭代对象)
const iterable = {
[Symbol.iterator]() {
let i = 0
return {
next() {
return i < 3
? { value: i++, done: false }
: { done: true }
}
}
}
}
// for...of 遍历
for (const item of iterable) {
console.log(item) // 0,1,2
}
// 生成器函数
function* counter() {
yield 1
yield 2
yield 3
}
const gen = counter()
gen.next().value // 1
十二、Set 和 Map
javascript
// Set(唯一值集合)
const set = new Set([1, 2, 2, 3]) // {1,2,3}
set.add(4)
set.has(2) // true
set.size // 4
// Map(键值对集合)
const map = new Map()
map.set('name', 'John')
map.get('name') // 'John'
map.has('name') // true
// WeakMap(弱引用,防止内存泄漏)
const wm = new WeakMap()
wm.set(obj, 'value') // 键必须是对象
十三、实用新方法
javascript
// 字符串
'hello'.includes('ell') // true
'hello'.startsWith('he') // true
'hello'.endsWith('lo') // true
'hi'.repeat(3) // 'hihihi'
// 数组
[1, 2, 3].find(x => x > 1) // 2
[1, 2, 3].findIndex(x => x > 1) // 1
[1, 2, 3].fill(0) // [0,0,0]
Array.from('abc') // ['a','b','c']
// 对象
Object.assign({}, {a:1}, {b:2}) // {a:1,b:2}
Object.entries({a:1,b:2}) // [['a',1],['b',2]]
Object.values({a:1,b:2}) // [1,2]
十四、常用模式示例
javascript
// 1. 合并对象(覆盖顺序从右到左)
const config = {
...defaultConfig,
...userConfig,
...overrides
}
// 2. 条件对象属性
const user = {
name: 'John',
...(isAdmin && { role: 'admin' })
}
// 3. 异步数据获取
async function loadData() {
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts()
])
return { user, posts }
}
// 4. 数据转换
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]
const userMap = new Map(
users.map(user => [user.id, user])
)
// 5. 错误处理包装
const safeGet = async (url) => {
try {
const res = await fetch(url)
return await res.json()
} catch {
return null
}
}
核心要点总结
-
let/const → 块级作用域变量
-
箭头函数 → 简写 + this绑定
-
解构 → 快速提取数据
-
模板字符串 → 字符串插值
-
扩展运算符 → 数组/对象操作
-
Class → 面向对象语法糖
-
模块化 → 代码组织
-
Promise/Async → 异步处理
-
新数据结构 → Set/Map
-
对象增强 → 简化对象操作
掌握这些核心语法,即可编写现代、简洁的 JavaScript 代码。