Appearance
JavaScript 速记表
基础语法
Hello World & 注释
// Hello Worldconsole.log("Hello, World!");// 单行注释/* 多行注释 可以换行 *//** * 文档注释 (JSDoc) * @param {string} name * @returns {string} */输入输出
// 输出console.log("Hello");console.error("Error message");console.warn("Warning");// 浏览器环境输入let name = prompt("Enter your name:");// Node.js 环境输入const readline = require('readline');const rl = readline.createInterface({ input: process.stdin, output: process.stdout});rl.question('Enter your name: ', (answer) => { console.log(`Hello, ${answer}`); rl.close();});变量与常量
声明方式
let mutable = 10 // 可变const immutable = 20 // 不可变var oldStyle = 30 // 不推荐(函数作用域)作用域
// 全局作用域var globalVar = 'global'function example() { // 函数作用域 var funcVar = 'function' if (true) { // 块级作用域 let blockVar = 'block' const blockConst = 'block' }}类型推断
动态类型,运行时确定
let x = 10 // numberx = "hello" // 可以改变类型const arr = [1, 2] // Array数据类型
基本类型
// 7 种基本类型let num = 42 // numberlet str = "hello" // stringlet bool = true // booleanlet nul = null // nulllet undef = undefined // undefinedlet sym = Symbol('id') // symbol (ES6)let big = 123n // bigint (ES2020)复合类型
// Objectconst obj = { name: 'Alice', age: 25 }// Arrayconst arr = [1, 2, 3]// Functionconst func = function() {}// Dateconst date = new Date()// RegExpconst regex = /pattern/g类型转换
// 转数字Number('42')parseInt('42')parseFloat('3.14')+'42'// 转字符串String(42)(42).toString()'' + 42// 转布尔Boolean(1)!!value类型检查
typeof valueArray.isArray(arr)value instanceof ClassObject.prototype.toString.call(value)Number.isNaN(value)Number.isFinite(value)运算符
算术运算符
+ - * / % // 加减乘除取模** // 幂运算 (ES2016)++ -- // 自增自减比较运算符
== != // 相等(类型转换)=== !== // 严格相等> < >= <= // 大小比较逻辑运算符
&& || ! // 与或非?? // 空值合并 (ES2020)?. // 可选链 (ES2020)value ?? 'default'obj?.prop?.method?.()位运算符
& | ^ ~ // 按位与或异或非<< >> >>> // 左移、右移、无符号右移赋值运算符
= += -= *= /= %=**= &= |= ^=<<= >>= >>>=&&= ||= ??= // 逻辑赋值 (ES2021)其他运算符
... // 展开运算符, // 逗号运算符?: // 三元运算符in // 属性检查delete // 删除属性字符串
声明和初始化
const str1 = 'single quotes'const str2 = "double quotes"const str3 = `template literal`const str4 = String(123)模板字符串
const name = 'Alice'const age = 25const msg = `Hello, ${name}! Age: ${age}`const multi = `Line 1Line 2Line 3`字符串方法
str.lengthstr.charAt(0)str.charCodeAt(0)str[0]str.indexOf('sub')str.lastIndexOf('sub')str.includes('sub')str.startsWith('pre')str.endsWith('suf')字符串操作
str.slice(0, 5)str.substring(0, 5)str.substr(0, 5)str.split(' ')str.repeat(3)str.concat(str2)str.trim()str.trimStart()str.trimEnd()str.padStart(10, '0')str.padEnd(10, ' ')大小写与替换
str.toLowerCase()str.toUpperCase()str.replace('old', 'new')str.replaceAll('old', 'new') // ES2021正则表达式
const regex = /pattern/gistr.match(/\d+/g)str.matchAll(/\d+/g)str.search(/pattern/)str.replace(/old/g, 'new')regex.test(str)regex.exec(str)集合数据结构
数组基础
const arr = [1, 2, 3]const arr2 = new Array(5)const arr3 = Array.of(1, 2, 3)const arr4 = Array.from('hello')数组方法
arr.push(4)arr.pop()arr.unshift(0)arr.shift()arr.splice(1, 2, 'a', 'b')arr.slice(1, 3)arr.concat(arr2)arr.join('-')arr.reverse()arr.sort()数组迭代
arr.map(x => x * 2)arr.filter(x => x > 0)arr.reduce((acc, x) => acc + x, 0)arr.forEach(x => console.log(x))arr.find(x => x > 5)arr.findIndex(x => x > 5)arr.some(x => x > 5)arr.every(x => x > 0)Map 映射
const map = new Map()map.set('key', 'value')map.get('key')map.has('key')map.delete('key')map.sizemap.clear()for (const [key, value] of map) {}Set 集合
const set = new Set([1, 2, 3])set.add(4)set.has(1)set.delete(1)set.sizeset.clear()for (const value of set) {}WeakMap 与 WeakSet
const wm = new WeakMap()const ws = new WeakSet()// 键必须是对象,弱引用const obj = {}wm.set(obj, 'value')ws.add(obj)控制流
if / else
if (condition) { // 执行} else if (otherCondition) { // 执行} else { // 执行}// 三元运算符const result = condition ? 'yes' : 'no'switch
switch (value) { case 1: console.log('one') break case 2: case 3: console.log('two or three') break default: console.log('other')}for 循环
for (let i = 0; i < 10; i++) { console.log(i)}for (const item of array) { console.log(item)}for (const key in object) { console.log(key, object[key])}while 循环
while (condition) { // 执行}do { // 至少执行一次} while (condition)跳转语句
break // 退出循环continue // 跳过本次return value // 返回值// 标签跳转outer: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) break outer }}函数
函数定义
// 函数声明function greet(name) { return `Hello, ${name}`} // 函数表达式const greet = function(name) { return `Hello, ${name}`} // 箭头函数const greet = (name) => `Hello, ${name}`const square = x => x * x参数
// 默认参数function greet(name = 'Guest') {}// 剩余参数function sum(...nums) { return nums.reduce((a, b) => a + b, 0)}// 解构参数function print({name, age}) {}高阶函数
// 函数作为参数function apply(fn, value) { return fn(value)}// 函数作为返回值function multiplier(factor) { return x => x * factor}闭包
function counter() { let count = 0 return { increment: () => ++count, decrement: () => --count, get: () => count }}const c = counter()c.increment()递归
function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1)}function fibonacci(n) { if (n <= 1) return n return fibonacci(n - 1) + fibonacci(n - 2)}面向对象
类定义
class Person { constructor(name, age) { this.name = name this.age = age } greet() { return `Hello, I'm ${this.name}` } static species = 'Homo sapiens'}继承
class Student extends Person { constructor(name, age, grade) { super(name, age) this.grade = grade } study() { console.log(`${this.name} is studying`) }}私有字段
ES2022
class BankAccount { #balance = 0 deposit(amount) { this.#balance += amount } getBalance() { return this.#balance }}Getter 和 Setter
class Circle { constructor(radius) { this._radius = radius } get area() { return Math.PI * this._radius ** 2 } set radius(value) { this._radius = value }}原型
function Person(name) { this.name = name}Person.prototype.greet = function() { return `Hello, I'm ${this.name}`} const p = new Person('Alice')异步编程
Promise
const promise = new Promise((resolve, reject) => { if (success) { resolve(data) } else { reject(error) }})promise .then(data => console.log(data)) .catch(error => console.error(error)) .finally(() => console.log('Done'))async/await
async function fetchData() { try { const response = await fetch(url) const data = await response.json() return data } catch (error) { console.error(error) }}Promise 方法
Promise.all([p1, p2, p3]) // 全部完成Promise.allSettled([p1, p2]) // 全部结束Promise.race([p1, p2]) // 最快完成Promise.any([p1, p2]) // 任一成功定时器
setTimeout(() => {}, 1000)setInterval(() => {}, 1000)clearTimeout(timerId)clearInterval(intervalId)错误处理
try/catch/finally
try { throw new Error('Something went wrong')} catch (error) { console.error(error.message) console.error(error.stack)} finally { console.log('Cleanup')}错误类型
ErrorSyntaxErrorReferenceErrorTypeErrorRangeErrorURIError自定义错误
class ValidationError extends Error { constructor(message) { super(message) this.name = 'ValidationError' }}throw new ValidationError('Invalid input')模块
ES6 模块
// 导出export const PI = 3.14export function add(a, b) {}export default class User {}// 导入import User from './user.js'import { PI, add } from './math.js'import * as Math from './math.js'import { add as sum } from './math.js'CommonJS
// 导出module.exports = { add, subtract }exports.PI = 3.14// 导入const { add } = require('./math')const math = require('./math')动态导入
// ES2020const module = await import('./module.js')import('./module.js').then(module => { module.doSomething()})文件操作
Node.js 文件读取
const fs = require('fs')// 同步读取const data = fs.readFileSync('file.txt', 'utf8')// 异步读取fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err console.log(data)})// Promise APIconst data = await fs.promises.readFile('file.txt', 'utf8')文件写入
// 同步写入fs.writeFileSync('file.txt', 'content')// 异步写入fs.writeFile('file.txt', 'content', err => { if (err) throw err})// 追加fs.appendFileSync('file.txt', 'more content')路径处理
const path = require('path')path.join('dir', 'file.txt')path.resolve('file.txt')path.dirname('/path/to/file.txt')path.basename('/path/to/file.txt')path.extname('file.txt')常用 API
JSON
JSON.stringify(obj)JSON.stringify(obj, null, 2) // 格式化JSON.parse(jsonString)Math
Math.random()Math.floor(3.7)Math.ceil(3.2)Math.round(3.5)Math.max(1, 2, 3)Math.min(1, 2, 3)Math.abs(-5)Math.pow(2, 3)Math.sqrt(16)Date
const now = new Date()const date = new Date('2024-01-01')date.getFullYear()date.getMonth() // 0-11date.getDate()date.getDay() // 0-6date.getTime()date.toISOString()date.toLocaleDateString()Console
console.log('message')console.error('error')console.warn('warning')console.table(array)console.time('label')console.timeEnd('label')console.trace()最佳实践
代码风格
// 使用 const/let,避免 varconst PI = 3.14let count = 0// 使用严格相等if (value === 42) {}// 使用箭头函数const fn = (x) => x * 2// 使用模板字符串const msg = `Hello, ${name}`性能优化
// 避免全局变量// 使用事件委托// 防抖和节流function debounce(fn, delay) { let timer return function(...args) { clearTimeout(timer) timer = setTimeout(() => fn(...args), delay) }}常见陷阱
// == vs ===0 == '0' // true0 === '0' // false// this 绑定const obj = { fn: function() { console.log(this) } }const fn = obj.fnfn() // this 指向 window/undefined// 闭包变量for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0) // 输出 3,3,3}工具链
包管理器
npm install packagenpm install -g packagenpm install --save-dev packageyarn add packageyarn global add packageyarn add -D packagepnpm install package构建工具
// Webpackwebpack --mode production// Vitevite build// Rolluprollup -c测试框架
// Jestnpm test// Vitestvitest// Mochamocha test/*.js代码格式化
// Prettierprettier --write .// ESLinteslint --fix .