JavaScript 核心入门 · 速查表
/ 11 min read
建议把这张表当作索引:每次用到某个 API 时回查 MDN,配合手写小 demo 记忆最快。内容有 20+ 个主题,覆盖本系列十章及常用运行时 API。
1. 变量声明
| 关键字 | 作用域 | 提升 | 重复声明 | 可重新赋值 |
|---|---|---|---|---|
var |
函数级 | 是(undefined) | 是 | 是 |
let |
块级 | 是(TDZ) | 否 | 是 |
const |
块级 | 是(TDZ) | 否 | 否(对象内容可变) |
优先
const→let→ 避免var
2. 数据类型(8 种)
- 原始类型:
undefinednullbooleannumberbigintstringsymbol - 引用类型:
object(含 array / function / date / regexp)
typeof 1 // "number"typeof "a" // "string"typeof true // "boolean"typeof undefined // "undefined"typeof null // "object" ← 历史 bugtypeof 1n // "bigint"typeof Symbol() // "symbol"typeof {} // "object"typeof function(){} // "function"Array.isArray([]) // true假值(falsy):false 0 -0 0n "" null undefined NaN —— 其余全为真值
3. 类型转换
Number("12") // 12Number("") // 0Number("12px") // NaNparseInt("12px") // 12parseFloat("1.5") // 1.5String(123) // "123"(123).toString(2) // "1111011"Boolean(0) // false+"3" // 3(一元加号)!!"" // false隐式转换规则
+有字符串则拼接,否则数值相加- * / %一律转数字==会做类型转换,===不会
1 == "1" // truenull == undefined // trueNaN == NaN // falseObject.is(NaN, NaN) // true4. 运算符
+ - * / % ** // 算术=== !== == != // 比较&& || ! // 逻辑(短路)?? // 空值合并(null/undefined 才取右)?. // 可选链? : // 三元= += -= *= /= %= **= // 赋值& | ^ ~ << >> >>> // 位运算0 ?? "默认" // 00 || "默认" // "默认"obj?.a?.b // 安全访问a ??= 1 // 仅当 a 为 null/undefined 时赋值5. 字符串方法
s.lengths[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-1Number.isInteger(x) Number.isNaN(x) Number.isFinite(x)parseInt(s, 10) parseFloat(s)
Math.abs/floor/ceil/round/truncMath.max(...arr) Math.min(...arr)Math.pow(2,3) Math.sqrt Math.cbrtMath.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 oo.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] = arrconst { x, y: alias, z = 2, ...others } = objconst { 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 / elseswitch (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...whilebreak / 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.innerTextel.setAttribute(k, v) el.getAttribute(k) el.removeAttribute(k)el.classList.add/remove/toggle/contains/replaceel.dataset.foo // data-fooel.style.color = "red"el.style.setProperty("--x", "1")
// 尺寸位置el.offsetWidth el.clientWidth el.scrollWidthel.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()判断 - 常用事件:
clickinputchangesubmitkeydownmouseoverscrollloadDOMContentLoaded
18. BOM & 存储
window.innerWidth / innerHeightwindow.location.href / pathname / search / hash / reload() / replace()window.history.pushState() / replaceState() / back()navigator.userAgentwindow.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 = 1export 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/gire.test(s) // 布尔re.exec(s) // 匹配数组 / nulls.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 记忆最快。