skip to content
我的博客

JavaScript 核心入门 · 速查表

/ 11 min read

建议把这张表当作索引:每次用到某个 API 时回查 MDN,配合手写小 demo 记忆最快。内容有 20+ 个主题,覆盖本系列十章及常用运行时 API。

1. 变量声明

关键字 作用域 提升 重复声明 可重新赋值
var 函数级 是(undefined) 是 是
let 块级 是(TDZ) 否 是
const 块级 是(TDZ) 否 否(对象内容可变)

优先 const → let → 避免 var


2. 数据类型(8 种)

  • 原始类型:undefined null boolean number bigint string symbol
  • 引用类型:object(含 array / function / date / regexp)
typeof 1 // "number"
typeof "a" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← 历史 bug
typeof 1n // "bigint"
typeof Symbol() // "symbol"
typeof {} // "object"
typeof function(){} // "function"
Array.isArray([]) // true

假值(falsy):false 0 -0 0n "" null undefined NaN —— 其余全为真值


3. 类型转换

Number("12") // 12
Number("") // 0
Number("12px") // NaN
parseInt("12px") // 12
parseFloat("1.5") // 1.5
String(123) // "123"
(123).toString(2) // "1111011"
Boolean(0) // false
+"3" // 3(一元加号)
!!"" // false

隐式转换规则

  • + 有字符串则拼接,否则数值相加
  • - * / % 一律转数字
  • == 会做类型转换,=== 不会
1 == "1" // true
null == undefined // true
NaN == NaN // false
Object.is(NaN, NaN) // true

4. 运算符

+ - * / % ** // 算术
=== !== == != // 比较
&& || ! // 逻辑(短路)
?? // 空值合并(null/undefined 才取右)
?. // 可选链
? : // 三元
= += -= *= /= %= **= // 赋值
& | ^ ~ << >> >>> // 位运算
0 ?? "默认" // 0
0 || "默认" // "默认"
obj?.a?.b // 安全访问
a ??= 1 // 仅当 a 为 null/undefined 时赋值

5. 字符串方法

s.length
s[0] s.at(-1) // 取字符
s.charAt(i) s.charCodeAt(i)
s.indexOf(x) s.lastIndexOf(x) s.includes(x)
s.startsWith(x) s.endsWith(x)
s.slice(a, b) // 支持负数
s.substring(a, b) // 自动交换、不认负数
s.split(",") // 切数组
s.replace(a, b) s.replaceAll(a, b)
s.toUpperCase() s.toLowerCase()
s.trim() s.trimStart() s.trimEnd()
s.padStart(5, "0") s.padEnd(5, "x")
s.repeat(3)
s.concat(x)
s.match(re) s.matchAll(re) s.search(re)

字符串不可变,所有方法返回新串


6. 数字 & Math

Number.MAX_SAFE_INTEGER // 2^53-1
Number.isInteger(x) Number.isNaN(x) Number.isFinite(x)
parseInt(s, 10) parseFloat(s)
Math.abs/floor/ceil/round/trunc
Math.max(...arr) Math.min(...arr)
Math.pow(2,3) Math.sqrt Math.cbrt
Math.random() // [0,1)
Math.sign Math.hypot
(3.14159).toFixed(2) // "3.14"
(255).toString(16) // "ff"

7. 数组方法

增删改

arr.push(x) // 末尾加,返回长度
arr.pop() // 末尾删,返回元素
arr.unshift(x) // 头部加
arr.shift() // 头部删
arr.splice(i, n, ...items) // 增删改(原地)
arr.slice(a, b) // 截取(不原地)
arr.concat(x) // 合并
arr.fill(v, a, b) // 填充
arr.copyWithin(t, s, e)
arr.reverse() // 原地反转
arr.sort((a,b)=>a-b) // 原地排序

查找

arr.indexOf(x) arr.lastIndexOf(x) arr.includes(x)
arr.find(fn) arr.findIndex(fn) arr.findLast(fn)
arr.at(-1)
arr.some(fn) arr.every(fn)

遍历 / 转换

arr.forEach(fn) // 无返回值
arr.map(fn) // 映射新数组
arr.filter(fn) // 过滤
arr.reduce((acc,v,i,a)=>acc+v, init)
arr.reduceRight(fn)
arr.flat(depth) arr.flatMap(fn)
arr.join("-")
arr.keys() arr.values() arr.entries()

静态

Array.isArray(x)
Array.from(iterable, fn) // 类数组/可迭代 → 数组
Array.of(1,2,3)

8. 对象

const o = { a: 1, "b-c": 2, [key]: 3, method(){}, get x(){}, set x(v){} }
o.a o["a"]
delete o.a
"a" in o
o.hasOwnProperty("a") // 推荐 Object.hasOwn(o, "a")
Object.keys(o) Object.values(o) Object.entries(o)
Object.assign(target, ...sources) // 浅拷贝/合并
Object.fromEntries(entries) // 转对象
Object.freeze(o) // 冻结(浅)
Object.seal(o) // 禁止增删,可改
Object.create(proto)
Object.getPrototypeOf(o) Object.setPrototypeOf(o, p)
Object.defineProperty(o, "k", { value, writable, enumerable, configurable })

遍历顺序:整数键升序 → 字符串键插入序 → Symbol 键插入序


9. 解构 & 展开

const [a, b = 1, ...rest] = arr
const { x, y: alias, z = 2, ...others } = obj
const { a: { b } } = obj // 嵌套
[...arr1, ...arr2]
{ ...obj1, ...obj2 } // 浅拷贝,后者覆盖
function f(...args) {}

10. 函数

function f(a, b = 1) {} // 声明(提升)
const f = function () {} // 表达式
const f = (a) => a * 2 // 箭头函数
const f = a => ({ a }) // 返回对象要加括号
(function(){})() // IIFE

箭头函数 vs 普通函数

箭头 普通
this 词法(外层) 调用时决定
arguments 无 有
new 不可 可
prototype 无 有

this 绑定优先级:new > bind/call/apply > obj.method() > 默认(严格 undefined / 非严格 window)

fn.call(ctx, a, b)
fn.apply(ctx, [a, b])
fn.bind(ctx, a) // 返回新函数

11. 作用域 & 闭包

  • 词法作用域:定义时确定,非调用时
  • 闭包:函数 + 其定义时的词法环境,可访问外部变量(即使外部已返回)
  • 用途:私有变量、柯里化、防抖节流、模块封装
  • 注意:可能造成内存不释放

12. 原型 & class

function Person(name) { this.name = name }
Person.prototype.say = function () {}
class Animal {
#secret = 1 // 私有字段
static count = 0 // 静态
constructor(name) { this.name = name }
get info() { return this.name }
set info(v) { this.name = v }
method() {}
static create() { return new Animal() }
}
class Dog extends Animal {
constructor(n) { super(n) } // 必须先 super
method() { super.method() }
}
  • prototype 是函数属性,__proto__/[[Prototype]] 是对象原型链
  • instanceof 沿原型链查找
  • 原型链顶端是 Object.prototype → null

13. 控制流

if / else if / else
switch (x) { case 1: break; default: }
for (let i = 0; i < n; i++) {}
for (const v of arr) {} // 值(可迭代)
for (const k in obj) {} // 键(含继承)
arr.forEach()
while / do...while
break / continue / label:

for...in 用于对象,for...of 用于数组/字符串/Map/Set


14. 异常处理

try { } catch (e) { } finally { }
throw new Error("msg")
class MyError extends Error {}
e.name e.message e.stack

finally 总执行;return 在 try 中也会先走 finally


15. 异步

Promise

new Promise((resolve, reject) => {})
p.then(onFulfilled, onRejected).catch(e => {}).finally(() => {})
Promise.all([p1, p2]) // 全成功才成功,任一失败即失败
Promise.allSettled([...]) // 等待全部,返回 {status, value|reason}
Promise.race([...]) // 第一个结束的
Promise.any([...]) // 第一个成功的
Promise.resolve(v) Promise.reject(e)

async / await

async function f() {
try {
const r = await fetch(url)
} catch (e) {}
}
// async 函数返回 Promise

事件循环

  • 同步代码 → 微任务(Promise.then、queueMicrotask、MutationObserver)→ 宏任务(setTimeout、setInterval、I/O、UI 渲染)
  • 每轮宏任务后清空所有微任务
setTimeout(fn, 0) // 宏任务
Promise.resolve().then(fn) // 微任务
queueMicrotask(fn)

16. DOM 操作

// 选择
document.getElementById(id)
document.querySelector(css)
document.querySelectorAll(css) // NodeList(静态)
document.getElementsByClassName(c) // HTMLCollection(动态)
el.closest(css) el.matches(css)
// 创建 / 插入
document.createElement(tag)
document.createTextNode(t)
parent.appendChild(el)
parent.insertBefore(el, ref)
el.append(...nodes) el.prepend() // 支持字符串
el.before() el.after() el.replaceWith()
el.remove()
el.cloneNode(true)
// 内容 / 属性
el.textContent // 纯文本(安全)
el.innerHTML // HTML(小心 XSS)
el.innerText
el.setAttribute(k, v) el.getAttribute(k) el.removeAttribute(k)
el.classList.add/remove/toggle/contains/replace
el.dataset.foo // data-foo
el.style.color = "red"
el.style.setProperty("--x", "1")
// 尺寸位置
el.offsetWidth el.clientWidth el.scrollWidth
el.getBoundingClientRect()
window.scrollTo({ top: 0, behavior: "smooth" })

17. 事件

el.addEventListener("click", handler, { capture, once, passive })
el.removeEventListener("click", handler)
e.target // 触发元素
e.currentTarget // 绑定元素
e.preventDefault()
e.stopPropagation() // 阻止冒泡
e.stopImmediatePropagation()
  • 冒泡:内 → 外;捕获:外 → 内
  • 事件委托:绑在父元素,用 e.target.closest() 判断
  • 常用事件:click input change submit keydown mouseover scroll load DOMContentLoaded

18. BOM & 存储

window.innerWidth / innerHeight
window.location.href / pathname / search / hash / reload() / replace()
window.history.pushState() / replaceState() / back()
navigator.userAgent
window.setTimeout(fn, ms) / clearTimeout(id)
window.setInterval(fn, ms) / clearInterval(id)
requestAnimationFrame(fn)
localStorage.setItem(k, v) // 永久,字符串
sessionStorage.setItem(k, v) // 会话
localStorage.getItem(k) removeItem(k) clear()
document.cookie // "a=1; b=2"
JSON.stringify / JSON.parse // 存对象

19. 模块

// 导出
export const a = 1
export default function () {}
export { a as b }
// 导入
import def from "./m.js"
import { a, b as c } from "./m.js"
import * as ns from "./m.js"
const m = await import("./m.js") // 动态导入

模块自动严格模式、作用域独立、只执行一次


20. Map / Set / WeakMap / WeakSet

const m = new Map([["k", 1]])
m.set(k, v) m.get(k) m.has(k) m.delete(k) m.clear()
m.size m.keys() m.values() m.entries()
// 键可为任意类型,保持插入序
const s = new Set([1, 2, 2])
s.add(x) s.has(x) s.delete(x) s.size
[...new Set(arr)] // 数组去重
new WeakMap() new WeakSet() // 键必须是对象,弱引用,不可遍历

21. Date

new Date()
new Date("2024-01-01")
new Date(2024, 0, 1) // 月从 0 开始
Date.now()
d.getFullYear() getMonth() getDate() getDay()
d.getHours() getMinutes() getSeconds() getMilliseconds()
d.getTime() d.toISOString() d.toLocaleDateString()
d.setFullYear() ...

22. 正则

const re = /abc/gi
re.test(s) // 布尔
re.exec(s) // 匹配数组 / null
s.match(re) s.matchAll(re) s.replace(re, "$1") s.split(re)
符号 含义
. 任意字符(除换行)
\d \w \s 数字 / 字母数字下划线 / 空白
^ $ 开头 / 结尾
* + ? {n,m} 量词
[] [^] 字符集 / 取反
() (?<name>) 分组 / 命名捕获
| 或
g i m s u y 全局 / 忽略大小写 / 多行 / dotAll / unicode / 粘连

23. JSON

JSON.stringify(obj) // → 字符串
JSON.stringify(obj, null, 2) // 格式化
JSON.stringify(obj, ["a", "b"]) // 只保留字段
JSON.parse(str)
JSON.parse(str, reviver)

会忽略:undefined、函数、Symbol;NaN/Infinity → null;循环引用报错


24. 迭代器 & 生成器

function* gen() {
yield 1
yield* [2, 3]
return 4
}
const it = gen()
it.next() // { value: 1, done: false }
// 自定义可迭代
const obj = { [Symbol.iterator]() { ... } }

可迭代对象:Array / String / Map / Set / arguments / NodeList


25. 常见坑

坑 说明
var 循环变量 setTimeout 里全拿到最终值,用 let 解决
浮点误差 0.1 + 0.2 !== 0.3,用 toFixed 或整数运算
sort() 默认字典序 [10,9,1].sort() → [1,10,9],需传比较函数
数组 length 可写 arr.length = 0 会清空
浅拷贝 [...] / {...} / Object.assign 只拷一层,深拷贝用 structuredClone()
this 丢失 回调中传方法需 bind 或箭头函数
NaN 判断 用 Number.isNaN(),别用 === NaN
for...in 遍历数组 会遍历原型链,用 for...of
闭包引用循环变量 用 let 或 IIFE 捕获
parseInt 无基数 显式传 10
直接改 innerHTML XSS 风险,优先 textContent
delete 数组元素 留空洞,用 splice

26. 严格模式

"use strict"
  • 未声明变量赋值报错
  • this 在普通函数中为 undefined
  • 禁止 with、重复参数名、八进制字面量
  • 模块和 class 内部自动严格

27. 性能 & 现代语法速查

structuredClone(obj) // 深拷贝(现代浏览器)
Array.prototype.at(-1)
Object.hasOwn(o, k)
String.prototype.replaceAll
?? ??= ||= &&=
#privateField // 真私有
static {} // 静态块
Array.prototype.findLast
  • 优先 const、纯函数、避免全局变量
  • 大量 DOM 操作先拼字符串/DocumentFragment
  • 频繁触发的操作用防抖 / 节流
  • 大数组用 for 循环优于 forEach(可 break)

💡 建议:把这张表当作索引,每次用到某个 API 时回查 MDN,配合手写小 demo 记忆最快。