JavaScript编程完全指南

← 返回指南列表

JavaScript编程完全指南

一、JavaScript概述

1.1 语言简介

JavaScript是一种高级、解释型(JIT编译)的编程语言,最初由Brendan Eich于1995年在Netscape公司创建,现已成为Web开发的核心语言。

核心特性:

特性 说明
解释型 通过JS引擎(V8、SpiderMonkey等)动态执行
弱类型 变量类型可动态改变,隐式类型转换
一等函数 函数可作为参数传递、从函数返回、赋值给变量
原型继承 基于原型链的对象继承机制
事件驱动 浏览器中的事件循环模型
单线程 主线程单线程,通过事件循环处理异步操作
跨平台 浏览器、Node.js、移动端、桌面端均可运行

1.2 发展历程

版本 发布时间 主要特性
ES3 1999年 try/catch、正则表达式
ES5 2009年 严格模式、JSON支持、数组方法(map/filter/reduce)
ES6/ES2015 2015年 箭头函数、class、let/const、Promise、模块、解构
ES2017 2017年 async/await、Object.values/entries
ES2018 2018年 展开运算符用于对象、异步迭代
ES2020 2020年 可选链(?.)、空值合并(??)、BigInt
ES2021 2021年 逻辑赋值运算符、String.replaceAll
ES2022 2022年 顶层await、类私有字段(#)、at()方法

1.3 运行环境

环境 JS引擎 典型用途
Chrome/Edge V8 Web前端
Firefox SpiderMonkey Web前端
Node.js V8 后端服务器
Deno V8 安全的TypeScript运行时
Bun JavaScriptCore 快速JS运行时
React Native JavaScriptCore/Hermes 移动端

1.4 应用领域

MERMAID
115%
Ctrl + 滚轮缩放 · 拖动查看完整流程图

1.5 开发环境

BASH
# Node.js安装(推荐使用nvm管理版本)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install --lts
nvm use --lts

# 验证安装
node --version
npm --version

# 常用IDE/编辑器
# VS Code + 推荐插件:ESLint, Prettier, JavaScript (ES6) code snippets, Live Server

二、基础语法详解

2.1 变量声明(var/let/const)

JAVASCRIPT
// ========== var:函数作用域,可重复声明,存在变量提升 ==========
var name = "JavaScript";
var name = "JS";          // 允许重复声明
console.log(name);        // JS

// 变量提升(hoisting)
console.log(hoisted);     // undefined(声明被提升,但赋值未提升)
var hoisted = "value";

// ========== let:块级作用域,不可重复声明 ==========
let age = 25;
// let age = 30;          // 报错:不允许重复声明

if (true) {
    let blockScoped = "只在此块内可见";
    console.log(blockScoped);  // 正常访问
}
// console.log(blockScoped);  // 报错:未定义

// ========== const:块级作用域,声明时必须赋值,不可重新赋值 ==========
const PI = 3.14159;
// PI = 3.14;               // 报错:不能重新赋值
// const EMPTY;             // 报错:必须赋值

// const 对象可修改属性,但不能重新赋值
const person = { name: "Alice" };
person.name = "Bob";        // 允许:修改属性
person.age = 30;            // 允许:添加属性
// person = {};             // 报错:不能重新赋值

// const 数组可修改元素
const arr = [1, 2, 3];
arr.push(4);                // 允许
arr[0] = 10;                // 允许
// arr = [5, 6];           // 报错

// ========== 作用域对比 ==========
var funcScoped = "var";
let blockScoped = "let";
const constant = "const";

{
    var x = 10;
    let y = 20;
    const z = 30;
}
console.log(x);  // 10(var可跨块访问)
// console.log(y); // 报错
// console.log(z); // 报错

2.2 数据类型

JavaScript有7种原始类型和1种复杂类型(Object)。

JAVASCRIPT
// ========== 7种原始类型(Primitive Types)==========

// 1. Number:双精度64位浮点数(IEEE 754)
let integer = 42;
let float = 3.14159;
let negative = -10;
let infinity = Infinity;
let negInfinity = -Infinity;
let notANumber = NaN;               // typeof NaN === 'number'
console.log(Number.MAX_VALUE);      // 1.7976931348623157e+308
console.log(Number.MIN_VALUE);      // 5e-324
console.log(Number.MAX_SAFE_INTEGER);  // 9007199254740991 (2^53-1)
console.log(Number.MIN_SAFE_INTEGER);  // -9007199254740991

// BigInt:任意精度整数(ES2020)
let bigInt = 9007199254740991n;
let bigInt2 = BigInt("9007199254740991");
console.log(typeof bigInt);         // 'bigint'

// 2. String:不可变的Unicode字符序列
let single = '单引号';
let double = "双引号";
let template = `模板字符串
可以换行
可以插值: ${1 + 1}`;

// 3. Boolean
let isTrue = true;
let isFalse = false;

// 4. Undefined:变量已声明但未赋值
let undefinedVar;
console.log(undefinedVar);          // undefined

// 5. Null:表示空值(故意的)
let nullVar = null;
console.log(typeof null);           // 'object'(历史遗留bug)

// 6. Symbol(ES6):唯一且不可变的值
let sym1 = Symbol("description");
let sym2 = Symbol("description");
console.log(sym1 === sym2);         // false(每个Symbol都是唯一的)
let sym3 = Symbol.for("key");       // 全局Symbol注册表
let sym4 = Symbol.for("key");
console.log(sym3 === sym4);         // true

// 7. Object(复杂类型)
let obj = { key: "value" };
let arr = [1, 2, 3];                // typeof arr === 'object'
let fn = function() {};             // typeof fn === 'function'
let date = new Date();
let regex = /pattern/;
let map = new Map();
let set = new Set();

typeof 运算符结果表

值 typeof 结果
undefined "undefined"
null "object"
true/false "boolean"
任意数字/NaN/Infinity "number"
9007199254740991n "bigint"
任意字符串 "string"
Symbol() "symbol"
函数 "function"
其他对象(数组/日期/正则/普通对象) "object"

类型转换与比较

JAVASCRIPT
// ========== 隐式类型转换(强制转换)==========
// 字符串 + 任何值 → 字符串
console.log("5" + 3);           // "53"
console.log("5" + true);        // "5true"

// 算术运算(除+外)→ 数值
console.log("5" - 3);           // 2
console.log("5" * "3");         // 15
console.log("10" / "2");        // 5

// 逻辑运算 → 布尔值
console.log(Boolean(""));       // false
console.log(Boolean("hello"));  // true

// ========== Falsy值(转为false的值)==========
// false, 0, -0, 0n, "", null, undefined, NaN

// ========== 显式转换 ==========
// 字符串 → 数字
console.log(Number("42"));      // 42
console.log(parseInt("42px"));  // 42
console.log(parseFloat("3.14.5")); // 3.14
console.log(+"42");             // 42

// 数字 → 字符串
console.log(String(42));        // "42"
console.log((42).toString());   // "42"
console.log(42 + "");           // "42"

// ========== 相等性比较 ==========
// == 宽松相等(会进行类型转换)
console.log(5 == "5");          // true
console.log(0 == false);        // true
console.log(null == undefined); // true
console.log("" == false);       // true

// === 严格相等(不进行类型转换,推荐使用)
console.log(5 === "5");         // false
console.log(0 === false);       // false
console.log(null === undefined); // false

// Object.is():更严格(区分+0和-0,NaN)
console.log(Object.is(NaN, NaN));    // true
console.log(NaN === NaN);            // false
console.log(Object.is(+0, -0));      // false
console.log(+0 === -0);              // true

2.3 运算符

JAVASCRIPT
// ========== 算术运算符 ==========
let a = 10, b = 3;
console.log(a + b);   // 13  加法
console.log(a - b);   // 7   减法
console.log(a * b);   // 30  乘法
console.log(a / b);   // 3.333... 除法(JS没有整数除法)
console.log(a % b);   // 1   取余
console.log(a ** b);  // 1000  指数(ES2016)
console.log(Math.floor(a / b));  // 3  模拟整数除法

// ========== 自增/自减 ==========
let x = 5;
console.log(x++);     // 5(后置:先返回再自增)
console.log(++x);     // 7(前置:先自增再返回)
console.log(x--);     // 7
console.log(--x);     // 5

// ========== 赋值运算符 ==========
let n = 10;
n += 5;   // n = 15
n -= 3;   // n = 12
n *= 2;   // n = 24
n /= 4;   // n = 6
n %= 4;   // n = 2
n **= 2;  // n = 4

// ========== 比较运算符 ==========
console.log(5 > 3);    // true
console.log(5 >= 5);   // true
console.log("abc" < "abd");  // true(字典序比较)

// ========== 逻辑运算符 ==========
console.log(true && false);   // false 逻辑与
console.log(true || false);   // true  逻辑或
console.log(!true);           // false 逻辑非

// 短路求值
console.log(0 && "hello");    // 0(遇到false停止)
console.log("" || "default"); // "default"(遇到true停止)
console.log(null ?? "fallback"); // "fallback"(空值合并,ES2020)
console.log(0 ?? "fallback"); // 0(0不是null/undefined)

// 可选链(ES2020)
const user = { profile: { name: "Alice" } };
console.log(user?.profile?.name);        // "Alice"
console.log(user?.address?.city);        // undefined(不会报错)

// ========== 位运算符 ==========
console.log(5 & 3);   // 1   (0101 & 0011 = 0001)
console.log(5 | 3);   // 7   (0101 | 0011 = 0111)
console.log(5 ^ 3);   // 6   (0101 ^ 0011 = 0110)
console.log(~5);      // -6  (~0101 = ...11111010)
console.log(5 << 1);  // 10  (0101 << 1 = 1010)
console.log(5 >> 1);  // 2   (0101 >> 1 = 0010)

// ========== 运算符优先级(从高到低)==========
// () → .[] → new → ++ -- → ! ~ → ** → * / % → + - → << >> → < <= → == === → & → ^ → | → && → || → ?? → ?: → = → ,

2.4 控制流

JAVASCRIPT
// ========== if/else ==========
const score = 85;

if (score >= 90) {
    console.log("A");
} else if (score >= 80) {
    console.log("B");       // 输出这个
} else if (score >= 70) {
    console.log("C");
} else {
    console.log("D");
}

// ========== 三元运算符 ==========
const status = score >= 60 ? "及格" : "不及格";
// 可以嵌套但不推荐
const level = score >= 90 ? "A" : score >= 80 ? "B" : "C";

// ========== switch ==========
const day = 3;
switch (day) {
    case 1:
        console.log("周一");
        break;
    case 2:
    case 3:
    case 4:
    case 5:
        console.log("工作日"); // day=3,匹配这里
        break;
    case 6:
    case 7:
        console.log("周末");
        break;
    default:
        console.log("无效日期");
}

// ========== for 循环 ==========
// 标准for
for (let i = 0; i < 5; i++) {
    console.log(i);  // 0, 1, 2, 3, 4
}

// for...of(遍历可迭代对象:数组、字符串、Map、Set)
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
    console.log(fruit);
}

// 使用 entries() 获取索引
for (const [index, fruit] of fruits.entries()) {
    console.log(`${index}: ${fruit}`);
}

// for...in(遍历对象可枚举属性,包括原型链)
const person = { name: "Alice", age: 25, city: "NYC" };
for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}
// 注意:for...in 也用于数组时会遍历索引(字符串形式),不推荐用于数组

// ========== while / do...while ==========
let count = 0;
while (count < 3) {
    console.log(count);  // 0, 1, 2
    count++;
}

let num = 0;
do {
    console.log(num);    // 0(至少执行一次)
    num++;
} while (num < 0);       // 条件为false,循环结束

// ========== break / continue ==========
for (let i = 0; i < 10; i++) {
    if (i === 3) continue;  // 跳过i=3
    if (i === 7) break;     // 在i=7退出
    console.log(i);          // 0, 1, 2, 4, 5, 6
}

// 标签语句(labeled statement)
outerLoop: for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (i === 1 && j === 1) break outerLoop;
        console.log(`(${i},${j})`);  // 输出到(1,0)为止
    }
}

2.5 函数定义

JAVASCRIPT
// ========== 函数声明 ==========
// 会被提升(hoisting)
function add(a, b) {
    return a + b;
}

// ========== 函数表达式 ==========
// 不会被提升
const multiply = function(a, b) {
    return a * b;
};

// ========== 箭头函数(ES6)==========
// 简洁语法
const subtract = (a, b) => a - b;
const square = x => x * x;           // 只有一个参数可省略括号

// 多行体需要 {} 和 return
const divide = (a, b) => {
    if (b === 0) throw new Error("除数不能为0");
    return a / b;
};

// 箭头函数没有自己的 this
// 箭头函数没有 arguments 对象
// 箭头函数不能用作构造函数

// ========== 参数处理 ==========
// 默认参数
function greet(name = "Guest", greeting = "Hello") {
    return `${greeting}, ${name}!`;
}
console.log(greet());              // "Hello, Guest!"
console.log(greet("Alice", "Hi")); // "Hi, Alice!"

// 剩余参数(Rest Parameters)
function sum(...numbers) {
    return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5));   // 15

// arguments 对象(仅普通函数可用)
function oldStyle() {
    console.log(arguments);        // 类数组对象
    return Array.from(arguments);  // 转为真数组
}

// ========== 立即执行函数表达式(IIFE)==========
(function() {
    const private = "私有变量";
    console.log(private);
})();

// 现代JS中多用块级作用域替代
{
    const private = "块级私有变量";
    console.log(private);
}

// ========== 高阶函数 ==========
// 接受函数作为参数
function operate(a, b, operation) {
    return operation(a, b);
}

console.log(operate(5, 3, add));         // 8
console.log(operate(5, 3, (x, y) => x - y)); // 2

// 返回函数(闭包)
function createCounter(initial = 0) {
    let count = initial;
    return {
        increment: () => ++count,
        decrement: () => --count,
        getValue: () => count
    };
}

const counter = createCounter(10);
console.log(counter.increment());  // 11
console.log(counter.increment());  // 12
console.log(counter.getValue());   // 12

// ========== 闭包(Closure)==========
// 函数可以记住并访问其词法作用域,即使函数在其作用域外执行
function makeAdder(x) {
    return function(y) {
        return x + y;  // 内部函数记住外部变量x
    };
}
const add5 = makeAdder(5);
console.log(add5(3));   // 8(5 + 3)
console.log(add5(10));  // 15(5 + 10)

2.6 this 关键字

this 的值取决于函数的调用方式。

JAVASCRIPT
// ========== this 的绑定规则 ==========

// 1. 全局上下文:this = window(浏览器)/ global(Node.js)
console.log(this);  // window

// 2. 函数调用:this = window(严格模式:undefined)
function showThis() {
    console.log(this);
}
showThis();  // window(非严格模式)

// 3. 方法调用:this = 调用方法的对象
const obj = {
    name: "MyObject",
    getName() {
        return this.name;
    }
};
console.log(obj.getName());  // "MyObject"

// 4. 构造函数调用:this = 新创建的对象
function Person(name) {
    this.name = name;
}
const p = new Person("Alice");
console.log(p.name);  // "Alice"

// 5. 箭头函数:继承外层作用域的 this
const obj2 = {
    name: "Obj2",
    regularFn: function() {
        console.log(this.name);  // "Obj2"
        const arrow = () => {
            console.log(this.name);  // "Obj2"(继承自regularFn)
        };
        arrow();
    }
};
obj2.regularFn();

// ========== 显式绑定 ==========
function greet(greeting) {
    return `${greeting}, ${this.name}!`;
}

const user = { name: "Bob" };

// call:立即调用,参数逐个传递
console.log(greet.call(user, "Hello"));   // "Hello, Bob!"

// apply:立即调用,参数作为数组传递
console.log(greet.apply(user, ["Hi"]));   // "Hi, Bob!"

// bind:返回新函数,不立即调用
const greetBob = greet.bind(user);
console.log(greetBob("Hey"));             // "Hey, Bob!"

// bind 可以部分应用参数
const sayHelloToBob = greet.bind(user, "Hello");
console.log(sayHelloToBob());             // "Hello, Bob!"

三、数据类型进阶

3.1 数组(Array)

JAVASCRIPT
// ========== 创建数组 ==========
const arr1 = [1, 2, 3, 4, 5];
const arr2 = new Array(5);             // 长度为5的空数组
const arr3 = Array.from("hello");      // ['h','e','l','l','o']
const arr4 = Array.from({length: 5}, (_, i) => i * 2);  // [0,2,4,6,8]
const arr5 = [...arr1];                // 浅拷贝

// ========== 添加/删除元素 ==========
let arr = [1, 2, 3];

arr.push(4);          // 末尾添加:[1,2,3,4]
arr.pop();            // 删除末尾:返回4
arr.unshift(0);       // 开头添加:[0,1,2,3]
arr.shift();          // 删除开头:返回0

// ========== splice:万能操作 ==========
arr = [1, 2, 3, 4, 5];
// splice(start, deleteCount, ...items)
arr.splice(2, 1, 99);       // 从索引2删1个,插入99 → [1,2,99,4,5]
arr.splice(1, 2);           // 从索引1删2个 → [1,4,5]
arr.splice(1, 0, 9, 10);    // 从索引1插入 → [1,9,10,4,5]

// ========== slice:截取(不修改原数组)==========
arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 4));  // [2,3,4](索引1-3)
console.log(arr.slice(2));     // [3,4,5]
console.log(arr.slice(-2));    // [4,5](倒数2个)

// ========== 遍历方法 ==========
const numbers = [1, 2, 3, 4, 5];

// forEach:遍历(无返回值,不能提前退出)
numbers.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});

// map:映射(返回新数组)
const doubled = numbers.map(x => x * 2);
console.log(doubled);  // [2,4,6,8,10]

// filter:过滤(返回新数组)
const evens = numbers.filter(x => x % 2 === 0);
console.log(evens);    // [2,4]

// reduce:归约
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum);      // 15

// reduceRight:从右向左归约
const chars = ["a", "b", "c"];
console.log(chars.reduceRight((a, b) => a + b));  // "cba"

// find:查找第一个满足条件的元素
const found = numbers.find(x => x > 3);
console.log(found);    // 4

// findIndex:查找第一个满足条件的索引
console.log(numbers.findIndex(x => x > 3));  // 3

// every:所有元素满足条件?
console.log(numbers.every(x => x > 0));  // true

// some:存在元素满足条件?
console.log(numbers.some(x => x > 4));   // true

// ========== 排序 ==========
const unsorted = [3, 1, 4, 1, 5, 9, 2, 6];
// sort 默认按字符串排序!
console.log([...unsorted].sort());  // [1,1,2,3,4,5,6,9]
// 数字排序需要比较函数
console.log([...unsorted].sort((a, b) => a - b));  // 升序
console.log([...unsorted].sort((a, b) => b - a));  // 降序

// reverse:反转
console.log([1, 2, 3].reverse());  // [3,2,1]

// toSorted / toReversed(ES2023,不修改原数组)
// const sorted = numbers.toSorted((a, b) => a - b);

// ========== 其他常用方法 ==========
console.log(numbers.includes(3));        // true
console.log(numbers.indexOf(3));         // 2
console.log(numbers.lastIndexOf(1));     // 最后出现的位置
console.log([1, 2].concat([3, 4]));      // [1,2,3,4]
console.log(["a", "b", "c"].join("-"));  // "a-b-c"
console.log([1, [2, [3]]].flat(2));      // [1,2,3](扁平化)
console.log([1, 2, 3].flatMap(x => [x, x * 2]));  // [1,2,2,4,3,6]
console.log("hello".split(""));           // ['h','e','l','l','o']

3.2 对象(Object)

JAVASCRIPT
// ========== 创建对象 ==========
// 对象字面量
const person = {
    name: "Alice",
    age: 25,
    "special-key": "value"  // 特殊键名必须加引号
};

// new Object()
const obj = new Object();
obj.key = "value";

// Object.create():指定原型创建
const proto = { greet() { return "Hello"; } };
const child = Object.create(proto);
console.log(child.greet());  // "Hello"

// ========== 属性访问 ==========
console.log(person.name);             // "Alice"
console.log(person["name"]);           // "Alice"
console.log(person["special-key"]);   // "value"
// .不能访问含特殊字符的键名

// ========== 属性操作 ==========
// 添加/修改
person.email = "alice@example.com";
person.age = 26;

// 删除
delete person.email;

// 检查属性是否存在
console.log("name" in person);              // true
console.log(person.hasOwnProperty("name")); // true(不包括原型链)

// 可选链访问(ES2020)
console.log(person?.address?.city);  // undefined(不会报错)

// ========== 计算属性名(ES6)==========
const key = "dynamicKey";
const dynamic = {
    [key]: "动态键名",
    [`prefix_${key}`]: "拼接键名"
};
console.log(dynamic.dynamicKey);  // "动态键名"

// ========== 属性描述符 ==========
const obj3 = {};
Object.defineProperty(obj3, "readOnly", {
    value: "不可修改",
    writable: false,   // 不可写
    enumerable: true,  // 可枚举
    configurable: false // 不可重新配置
});

// ========== 对象方法 ==========
const user = { name: "Alice", age: 25, city: "NYC" };

// 获取属性
console.log(Object.keys(user));      // ["name","age","city"]
console.log(Object.values(user));    // ["Alice",25,"NYC"]
console.log(Object.entries(user));   // [["name","Alice"],...]

// 合并对象
const merged = Object.assign({}, user, { age: 26, hobby: "coding" });
console.log(merged);  // 浅拷贝 + 属性覆盖

// 冻结/密封
const frozen = Object.freeze({ x: 1 });   // 完全不可变
// frozen.x = 2;  // 静默失败(严格模式报错)

const sealed = Object.seal({ x: 1 });     // 不可添加/删除,可修改
sealed.x = 2;  // 允许

// 获取原型
console.log(Object.getPrototypeOf([]));    // Array.prototype

// ========== 解构赋值(ES6)==========
const { name, age, city: location = "Unknown" } = person;
// city 重命名为 location,带默认值
console.log(name, age, location);

// 嵌套解构
const complex = { 
    user: { 
        profile: { firstName: "Bob", lastName: "Smith" } 
    } 
};
const { user: { profile: { firstName, lastName } } } = complex;

// 剩余属性
const { name: userName, ...rest } = person;
console.log(userName, rest);  // "Alice", {age: 26}

// ========== 展开运算符(ES2018)==========
const defaults = { theme: "light", language: "en" };
const settings = { ...defaults, theme: "dark" };  // 覆盖
console.log(settings);  // {theme:"dark", language:"en"}

// ========== 方法简写(ES6)==========
const calculator = {
    value: 0,
    add(n) {           // 简写:add: function(n) 的语法糖
        this.value += n;
        return this;
    },
    getValue() {
        return this.value;
    }
};

3.3 Map 与 Set

JAVASCRIPT
// ========== Map:键值对集合,键可以是任意类型 ==========
const map = new Map();

// 设置/获取
map.set("name", "Alice");
map.set(42, "the answer");
map.set({ id: 1 }, "object key");
map.set(true, "boolean key");

console.log(map.get("name"));        // "Alice"
console.log(map.get(42));            // "the answer"
console.log(map.has("name"));        // true
console.log(map.size);               // 4

// Map 与 Object 的区别:
// - Map 键可以是任意类型,Object 键只能是字符串或Symbol
// - Map 保持插入顺序,Object 键顺序不保证
// - Map 有 size 属性,Object 需 Object.keys().length
// - Map 可直接迭代,Object 需先取 keys/values/entries

// 遍历Map
for (const [key, value] of map) {
    console.log(key, value);
}
map.forEach((value, key) => {
    console.log(key, value);
});
console.log([...map.keys()]);     // 所有键
console.log([...map.values()]);   // 所有值

// 删除
map.delete("name");
map.clear();

// ========== WeakMap:键必须是对象,弱引用(不影响GC)==========
const weakMap = new WeakMap();
let obj = { id: 1 };
weakMap.set(obj, "data");
console.log(weakMap.get(obj));  // "data"
obj = null;  // 此时 'data' 可被垃圾回收
// WeakMap 不可遍历,没有 size 属性

// ========== Set:唯一值的集合 ==========
const set = new Set([1, 2, 3, 3, 4, 4]);
console.log(set);                 // Set(4) {1, 2, 3, 4}

// 操作
set.add(5);
set.add(1);                       // 已存在,忽略
console.log(set.has(3));          // true
console.log(set.size);            // 5
set.delete(2);
console.log(set);                 // {1, 3, 4, 5}

// 集合运算
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

// 并集
const union = new Set([...setA, ...setB]);  // {1,2,3,4}
// 交集
const intersection = new Set([...setA].filter(x => setB.has(x)));  // {2,3}
// 差集
const difference = new Set([...setA].filter(x => !setB.has(x)));   // {1}

// 数组去重
const duplicates = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(duplicates)];  // [1,2,3,4]

// ========== WeakSet:值必须是对象,弱引用 ==========
const visitedNodes = new WeakSet();
// visitedNodes 中的对象可被GC

3.4 字符串进阶

JAVASCRIPT
const str = "Hello, World!";

// ========== 常用方法 ==========
console.log(str.length);                  // 13
console.log(str.charAt(0));               // "H"
console.log(str.charCodeAt(0));           // 72(ASCII码)
console.log(str.toUpperCase());           // "HELLO, WORLD!"
console.log(str.toLowerCase());           // "hello, world!"

// 查找
console.log(str.indexOf("World"));        // 7
console.log(str.includes("Hello"));       // true
console.log(str.startsWith("He"));        // true
console.log(str.endsWith("!"));           // true

// 截取
console.log(str.slice(0, 5));             // "Hello"(支持负数)
console.log(str.substring(0, 5));         // "Hello"(不支持负数)
console.log(str.substr(0, 5));            // "Hello"(已废弃)

// 替换
console.log(str.replace("World", "JS"));     // "Hello, JS!"
console.log(str.replaceAll("l", "L"));       // "HeLLo, WorLd!"(ES2021)

// 分割/拼接
console.log(str.split(", "));             // ["Hello", "World!"]
console.log(["a", "b"].join("-"));        // "a-b"

// 空白处理
console.log("  hello  ".trim());          // "hello"
console.log("  hello  ".trimStart());     // "hello  "
console.log("  hello  ".trimEnd());       // "  hello"

// 填充
console.log("42".padStart(5, "0"));       // "00042"
console.log("42".padEnd(5, "0"));         // "42000"

// 重复
console.log("ha".repeat(3));              // "hahaha"

// ========== 模板字符串 ==========
const name = "Alice", age = 25;
const greeting = `我是${name},今年${age}岁,明年${age + 1}岁`;
const multiLine = `
    第一行
    第二行
    可以包含表达式: ${2 + 2}
`;

// 标签模板(Tagged Templates)
function highlight(strings, ...values) {
    return strings.reduce((result, str, i) => {
        return result + str + (values[i] ? `<em>${values[i]}</em>` : "");
    }, "");
}
console.log(highlight`Hello ${name}, age ${age}`);

// ========== 正则表达式 ==========
const text = "The quick brown fox jumps over 123 lazy dogs.";

// 字面量
const regex1 = /fox/;
// 构造函数
const regex2 = new RegExp("dog", "i");  // i = 忽略大小写

// 常用标志
// g: 全局匹配, i: 忽略大小写, m: 多行模式, s: .匹配换行, u: Unicode模式

// 测试
console.log(/fox/.test(text));            // true

// 查找
console.log(text.match(/\d+/));           // ["123"]
console.log(text.match(/\d+/g));          // ["123"]

// 替换
console.log(text.replace(/\d+/, "数字"));   // "... over 数字 lazy dogs."

// 查找索引
console.log(text.search(/fox/));          // 16

// 分割
console.log(text.split(/\s+/));           // 按空白分割

// exec:逐步匹配(有状态)
const re = /(\w+)/g;
let match;
while ((match = re.exec(text)) !== null) {
    console.log(match[1]);  // 逐个打印单词
}

四、面向对象编程

4.1 构造函数与原型

JAVASCRIPT
// ========== 构造函数(旧方式)==========
function Animal(name) {
    this.name = name;
}

// 方法添加到原型(所有实例共享)
Animal.prototype.speak = function() {
    return `${this.name} makes a sound.`;
};

// 静态方法(直接挂在构造函数上)
Animal.compare = function(a, b) {
    return a.name.localeCompare(b.name);
};

const dog = new Animal("Dog");
console.log(dog.speak());     // "Dog makes a sound."

// ========== 原型链 ==========
// 每个对象都有 [[Prototype]](__proto__)
// 函数的 prototype 属性指向其原型对象
// 实例的 __proto__ 指向构造函数的 prototype

console.log(dog.__proto__ === Animal.prototype);         // true
console.log(Animal.prototype.__proto__ === Object.prototype); // true
console.log(Object.prototype.__proto__);                 // null(原型链终点)

// ========== Object.create() 继承 ==========
const mammal = {
    breathe() { return "Breathing..."; }
};

const cat = Object.create(mammal);
cat.meow = function() { return "Meow!"; };

console.log(cat.breathe());  // "Breathing..."(继承自mammal)
console.log(cat.meow());     // "Meow!"

// ========== 继承(构造函数方式)==========
function Dog(name, breed) {
    Animal.call(this, name);  // 调用父类构造函数
    this.breed = breed;
}

// 设置原型链继承
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;  // 修复 constructor 指向

// 添加子类方法
Dog.prototype.bark = function() {
    return `${this.name} barks!`;
};

const myDog = new Dog("Buddy", "Golden Retriever");
console.log(myDog.speak());   // "Buddy makes a sound."
console.log(myDog.bark());    // "Buddy barks!"

4.2 ES6 类(Class)

JAVASCRIPT
// ========== 类声明 ==========
class Person {
    // 私有字段(ES2022),用 # 前缀
    #age;  // 真正私有

    // 静态字段
    static species = "Homo Sapiens";

    // 构造方法
    constructor(name, age) {
        this.name = name;  // 公开属性
        this.#age = age;   // 私有属性
    }

    // Getter
    get age() {
        return this.#age;
    }

    // Setter
    set age(value) {
        if (value < 0 || value > 150) {
            throw new Error("无效年龄");
        }
        this.#age = value;
    }

    // 实例方法
    greet() {
        return `Hello, I'm ${this.name}, ${this.#age} years old.`;
    }

    // 静态方法
    static isAdult(age) {
        return age >= 18;
    }

    // 私有方法(ES2022)
    #privateMethod() {
        return "私有信息";
    }

    getPrivateInfo() {
        return this.#privateMethod();
    }
}

const person = new Person("Alice", 25);
console.log(person.greet());         // "Hello, I'm Alice, 25 years old."
console.log(person.age);             // 25(通过getter访问)
person.age = 30;                     // 通过setter设置
console.log(Person.isAdult(20));     // true(静态方法)
// console.log(person.#age);         // 语法错误:私有字段不可外部访问

// ========== 继承 ==========
class Student extends Person {
    static schoolName = "MIT";

    constructor(name, age, studentId) {
        super(name, age);  // 必须先调用 super()
        this.studentId = studentId;
    }

    // 重写父类方法
    greet() {
        return `${super.greet()} Student ID: ${this.studentId}`;
    }

    study(subject) {
        return `${this.name} is studying ${subject}.`;
    }

    // 静态方法也可继承
    static getSchool() {
        return this.schoolName;
    }
}

const student = new Student("Bob", 20, "S12345");
console.log(student.greet());        // "Hello, I'm Bob, 20... Student ID: S12345"
console.log(student.study("Math"));  // "Bob is studying Math."
console.log(student instanceof Person);  // true
console.log(student instanceof Student); // true

4.3 多态与鸭子类型

JAVASCRIPT
// ========== 鸭子类型:如果它走路像鸭子,叫起来像鸭子,它就是鸭子 ==========
// JavaScript通过共享的方法签名实现多态

class Duck {
    speak() { return "Quack!"; }
    swim() { return "Duck swimming"; }
}

class Dog {
    speak() { return "Woof!"; }
    swim() { return "Dog swimming"; }
}

class Fish {
    speak() { return "..." ; }
    swim() { return "Fish swimming"; }
}

// 只要对象有 speak 和 swim 方法,就可以被处理
function makeItSpeak(animal) {
    console.log(animal.speak());
}

makeItSpeak(new Duck());  // "Quack!"
makeItSpeak(new Dog());   // "Woof!"
makeItSpeak(new Fish());  // "..."

4.4 Mixin 模式

JAVASCRIPT
// ========== Mixin:通过组合共享行为 ==========

// 定义可复用的行为
const TimestampMixin = Base => class extends Base {
    getTimestamp() {
        return new Date().toISOString();
    }
};

const LoggerMixin = Base => class extends Base {
    log(message) {
        console.log(`[${this.getTimestamp()}] ${message}`);
    }
};

const SerializableMixin = Base => class extends Base {
    toJSON() {
        return JSON.stringify(this);
    }
};

// 组合Mixin
class BaseEntity {
    constructor(id) {
        this.id = id;
    }
}

class User extends TimestampMixin(LoggerMixin(SerializableMixin(BaseEntity))) {
    constructor(id, name) {
        super(id);
        this.name = name;
    }
}

const user = new User(1, "Alice");
user.log("用户创建");       // [2024-06-15T10:30:00.000Z] 用户创建
console.log(user.toJSON()); // {"id":1,"name":"Alice"}

五、异步编程

5.1 事件循环(Event Loop)

JAVASCRIPT
// ========== JavaScript 单线程执行模型 ==========
// 1. 同步代码在调用栈(Call Stack)中执行
// 2. 异步操作进入Web APIs/Node APIs
// 3. 完成后回调进入任务队列(Task Queue)
// 4. 调用栈清空后,事件循环取任务队列中的回调执行

// ========== 宏任务(MacroTask)==========
// setTimeout, setInterval, I/O, UI渲染, setImmediate(Node)

// ========== 微任务(MicroTask)==========
// Promise.then/catch/finally, queueMicrotask, MutationObserver

// ========== 执行顺序示例 ==========
console.log("1. 同步代码");

setTimeout(() => {
    console.log("4. setTimeout(宏任务)");
}, 0);

Promise.resolve().then(() => {
    console.log("3. Promise.then(微任务)");
});

console.log("2. 同步代码");

// 输出顺序:1 → 2 → 3 → 4
// 原因:微任务优先级高于宏任务

5.2 回调函数

JAVASCRIPT
// ========== 传统回调模式 ==========
function fetchData(url, callback) {
    setTimeout(() => {
        const success = Math.random() > 0.5;
        if (success) {
            callback(null, { data: "response data", url });
        } else {
            callback(new Error("网络请求失败"), null);
        }
    }, 1000);
}

// 使用回调
fetchData("https://api.example.com", (error, result) => {
    if (error) {
        console.error("错误:", error.message);
        return;  // 提前返回避免继续执行
    }
    console.log("成功:", result);
});

// ========== 回调地狱(Callback Hell)==========
// fetchData("url1", (err, data1) => {
//     if (err) return;
//     fetchData("url2", (err, data2) => {
//         if (err) return;
//         fetchData("url3", (err, data3) => {
//             if (err) return;
//             // 嵌套越来越深...
//         });
//     });
// });

5.3 Promise

JAVASCRIPT
// ========== 创建 Promise ==========
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const fetchUser = (id) => new Promise((resolve, reject) => {
    setTimeout(() => {
        if (id > 0) {
            resolve({ id, name: `User${id}`, email: `user${id}@example.com` });
        } else {
            reject(new Error(`无效用户ID: ${id}`));
        }
    }, 1000);
});

// ========== Promise 状态 ==========
// pending(进行中)→ fulfilled(成功)或 rejected(失败)
// 状态一旦改变就不能再变

// ========== then/catch/finally ==========
fetchUser(1)
    .then(user => {
        console.log("用户:", user);
        return user.name;  // 返回的值会包装为 Promise
    })
    .then(name => {
        console.log("用户名:", name);
    })
    .catch(error => {
        console.error("错误:", error.message);
    })
    .finally(() => {
        console.log("请求结束(无论成功失败)");
    });

// ========== Promise 静态方法 ==========
// Promise.all:全部成功才成功,一个失败即失败
Promise.all([
    fetchUser(1),
    fetchUser(2),
    fetchUser(3),
]).then(users => {
    console.log("所有用户:", users);
}).catch(err => {
    console.error("至少一个请求失败:", err);
});

// Promise.allSettled:等待全部完成,不论成败(ES2020)
Promise.allSettled([
    fetchUser(1),
    fetchUser(-1),  // 这个会失败
    fetchUser(3),
]).then(results => {
    results.forEach((result, i) => {
        if (result.status === "fulfilled") {
            console.log(`请求${i}成功:`, result.value);
        } else {
            console.log(`请求${i}失败:`, result.reason.message);
        }
    });
});

// Promise.race:第一个完成的(不论成败)
Promise.race([
    fetchUser(1),
    delay(500).then(() => "timeout"),
]).then(result => console.log("Race结果:", result));

// Promise.any:第一个成功的,全失败则拒绝(ES2021)
Promise.any([
    Promise.reject(new Error("失败1")),
    Promise.reject(new Error("失败2")),
    fetchUser(1),
]).then(result => console.log("Any成功:", result));

// Promise.resolve / Promise.reject
const resolved = Promise.resolve("直接成功");
const rejected = Promise.reject(new Error("直接失败"));

5.4 async/await

JAVASCRIPT
// ========== async 函数 ==========
// async 函数总是返回 Promise
async function getData() {
    return "data";  // 等同于 return Promise.resolve("data")
}
// getData().then(data => console.log(data));

// ========== await 关键字 ==========
// await 只能在 async 函数内使用
// await 暂停函数执行,直到 Promise 完成

async function loadUserProfile(userId) {
    try {
        console.log("开始加载...");
        
        // 顺序执行(总共3秒)
        const user = await fetchUser(userId);
        const posts = await fetchUserPosts(user.id);
        const comments = await fetchUserComments(user.id);
        
        console.log("加载完成:", { user, posts, comments });
        return { user, posts, comments };
        
    } catch (error) {
        console.error("加载失败:", error.message);
        throw error;  // 重新抛出
    }
}

// ========== 并行 vs 串行 ==========
async function loadParallel() {
    // 并行:同时发起所有请求(约1秒)
    const [user, posts, comments] = await Promise.all([
        fetchUser(1),
        fetchUserPosts(1),
        fetchUserComments(1),
    ]);
    return { user, posts, comments };
}

// ========== 错误处理模式 ==========
// 方式1:try/catch
async function withTryCatch() {
    try {
        const data = await fetchUser(-1);
    } catch (err) {
        console.error("try/catch捕获:", err);
    }
}

// 方式2:.catch()
async function withCatch() {
    const data = await fetchUser(-1).catch(err => {
        console.error(".catch捕获:", err);
        return null;  // 提供默认值
    });
}

// 方式3:包装函数(Go风格的错误处理)
async function to(promise) {
    try {
        return [null, await promise];
    } catch (error) {
        return [error, null];
    }
}

async function goStyle() {
    const [err, user] = await to(fetchUser(1));
    if (err) {
        console.error("错误:", err);
        return;
    }
    console.log("成功:", user);
}

// ========== 顶层 await(ES2022,模块中可用)==========
// const data = await fetch("https://api.example.com").json();

// ========== async 迭代器(ES2018)==========
async function* asyncGenerator() {
    yield await fetchUser(1);
    yield await fetchUser(2);
    yield await fetchUser(3);
}

(async () => {
    for await (const user of asyncGenerator()) {
        console.log("迭代:", user.name);
    }
})();

六、错误处理

6.1 try/catch/finally

JAVASCRIPT
// ========== 基本语法 ==========
function parseUserJSON(jsonStr) {
    try {
        const user = JSON.parse(jsonStr);
        if (!user.name) {
            throw new Error("缺少name字段");
        }
        return user;
    } catch (error) {
        if (error instanceof SyntaxError) {
            console.error("JSON格式错误:", error.message);
        } else {
            console.error("其他错误:", error.message);
        }
        return null;
    } finally {
        console.log("解析完成");  // 总是执行
    }
}

// ========== 自定义错误类 ==========
class ValidationError extends Error {
    constructor(message, field) {
        super(message);
        this.name = "ValidationError";
        this.field = field;
    }
}

class NetworkError extends Error {
    constructor(message, statusCode) {
        super(message);
        this.name = "NetworkError";
        this.statusCode = statusCode;
    }
}

// ========== 全局错误捕获 ==========
// 浏览器:window.onerror / window.addEventListener('error')
// window.onerror = (message, source, lineno, colno, error) => {
//     console.error("全局错误:", message, error);
// };

// 未捕获的Promise拒绝
// window.addEventListener('unhandledrejection', event => {
//     console.error("未处理的Promise拒绝:", event.reason);
//     event.preventDefault();  // 阻止默认行为
// });

// Node.js
// process.on('uncaughtException', (error) => {
//     console.error("未捕获异常:", error);
// });
// process.on('unhandledRejection', (reason, promise) => {
//     console.error("未处理拒绝:", reason);
// });

6.2 防御性编程

JAVASCRIPT
// ========== 空值安全 ==========
// 使用可选链
const city = user?.address?.city ?? "Unknown";

// 使用默认值
function greet(name = "Guest") {
    return `Hello, ${name}!`;
}

// ========== 类型检查 ==========
function addNumbers(a, b) {
    if (typeof a !== "number" || typeof b !== "number") {
        throw new TypeError("参数必须是数字");
    }
    return a + b;
}

// ========== 输入验证 ==========
function createUser(data) {
    const { name, email, age } = data ?? {};
    
    if (!name?.trim()) throw new ValidationError("名称不能为空", "name");
    if (!email?.includes("@")) throw new ValidationError("邮箱格式无效", "email");
    if (age !== undefined && (age < 0 || age > 150)) {
        throw new ValidationError("年龄无效", "age");
    }
    
    return { name: name.trim(), email, age };
}

七、DOM操作

7.1 元素选择与操作

JAVASCRIPT
// ========== 选择元素 ==========
const byId = document.getElementById("myId");
const byClass = document.getElementsByClassName("myClass");    // HTMLCollection(动态)
const byTag = document.getElementsByTagName("div");            // HTMLCollection(动态)
const byName = document.getElementsByName("username");         // NodeList(动态)

// CSS选择器(推荐)
const single = document.querySelector(".container > .item");   // 第一个匹配
const all = document.querySelectorAll(".item");                // NodeList(静态)
all.forEach(el => console.log(el));                            // 可遍历

// 关系导航
const parent = element.parentElement;
const children = element.children;              // HTMLCollection
const first = element.firstElementChild;
const last = element.lastElementChild;
const next = element.nextElementSibling;
const prev = element.previousElementSibling;
const closest = element.closest(".container");  // 向上查找最近的匹配元素

// ========== 修改内容和属性 ==========
// 文本内容
element.textContent = "纯文本(安全)";
element.innerText = "纯文本(考虑CSS隐藏)";
element.innerHTML = "<strong>HTML内容(注意XSS风险)</strong>";

// 属性
element.setAttribute("data-id", "123");
element.getAttribute("data-id");
element.removeAttribute("data-id");
element.hasAttribute("data-id");
// HTML5 data-* 属性快捷方式
element.dataset.id = "123";   // 对应 data-id="123"
console.log(element.dataset.id);

// 类名操作(推荐使用classList)
element.classList.add("active", "highlight");
element.classList.remove("hidden");
element.classList.toggle("visible");
element.classList.contains("active");
element.classList.replace("old", "new");

// 样式
element.style.color = "red";
element.style.setProperty("--custom-color", "blue");
const styles = getComputedStyle(element);  // 最终计算样式(只读)

// ========== 创建和操作节点 ==========
// 创建
const div = document.createElement("div");
div.textContent = "新创建的元素";

// 插入
parent.appendChild(div);                     // 追加到末尾
parent.insertBefore(div, referenceNode);     // 插入到引用节点之前
parent.prepend(div);                         // 追加到开头(现代API)
parent.append(div, "文本", anotherElement);  // 追加多个(现代API)
referenceNode.before(newNode);              // 插入到前面(现代API)
referenceNode.after(newNode);               // 插入到后面(现代API)
referenceNode.replaceWith(newNode);          // 替换(现代API)

// 移除
element.remove();                            // 现代API
// parent.removeChild(element);              // 旧API

// 克隆
const clone = element.cloneNode(true);       // true=深克隆,false=浅克隆

// ========== DOM属性 vs HTML属性 ==========
// DOM属性:element.value(当前值)
// HTML属性:element.getAttribute("value")(初始值)
const input = document.querySelector("input");
input.value = "新值";       // 修改DOM属性(显示在页面)
input.setAttribute("value", "新值");  // 修改HTML属性(显示在源码)

7.2 事件处理

JAVASCRIPT
// ========== 添加事件监听器 ==========
const button = document.querySelector("button");

// 方式1:addEventListener(推荐,支持多个监听器)
button.addEventListener("click", function(event) {
    console.log("按钮被点击");
    console.log("事件目标:", event.target);
    console.log("当前元素:", event.currentTarget);
    console.log("事件类型:", event.type);
});

// 方式2:onevent 属性(只能绑定一个)
// button.onclick = function() {};

// 方式3:HTML内联(不推荐,关注点分离)
// <button onclick="handleClick()">

// ========== 事件选项 ==========
// { once: true }:只触发一次
button.addEventListener("click", () => {
    console.log("只触发一次");
}, { once: true });

// { capture: true }:捕获阶段触发(默认为冒泡阶段)
// { passive: true }:不调用preventDefault(提升滚动性能)

// ========== 事件传播 ==========
// 事件传播三阶段:
// 1. 捕获阶段(Capture):从window到目标元素
// 2. 目标阶段(Target):事件到达目标元素
// 3. 冒泡阶段(Bubble):从目标元素冒泡回window

// 阻止冒泡
document.querySelector(".inner").addEventListener("click", (e) => {
    e.stopPropagation();  // 阻止事件向上冒泡
    console.log("内部元素(不会冒泡到外部)");
});

document.querySelector(".outer").addEventListener("click", () => {
    console.log("外部元素");
});

// 阻止默认行为
document.querySelector("a").addEventListener("click", (e) => {
    e.preventDefault();  // 阻止链接跳转
    console.log("链接点击被阻止");
});

// ========== 事件委托 ==========
// 利用冒泡,在父元素上监听子元素事件
// 优势:减少监听器数量,动态元素无需重新绑定

const todoList = document.querySelector("#todo-list");

// 不需要给每个li绑定事件
todoList.addEventListener("click", (e) => {
    // 检查是否点击了目标元素
    if (e.target.matches(".todo-item")) {
        console.log("点击了:", e.target.textContent);
    }
    
    if (e.target.matches(".delete-btn")) {
        e.target.closest(".todo-item").remove();
    }
});

// ========== 常用事件类型 ==========
// 鼠标: click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave, mouseover, mouseout, contextmenu
// 键盘: keydown, keyup, keypress
// 表单: submit, input, change, focus, blur
// 文档/窗口: DOMContentLoaded, load, resize, scroll, beforeunload
// 触摸: touchstart, touchmove, touchend
// 拖拽: drag, dragstart, dragend, dragover, drop
// 剪贴板: copy, cut, paste

// ========== 自定义事件 ==========
// 创建
const customEvent = new CustomEvent("userLogin", {
    detail: { userId: 123, username: "alice" },
    bubbles: true,
    cancelable: true
});

// 触发
element.dispatchEvent(customEvent);

// 监听
document.addEventListener("userLogin", (e) => {
    console.log("自定义事件:", e.detail);
});

7.3 表单处理

JAVASCRIPT
// ========== 表单事件和取值 ==========
const form = document.querySelector("form");

form.addEventListener("submit", (e) => {
    e.preventDefault();  // 阻止默认提交

    // 方式1:FormData API
    const formData = new FormData(form);
    for (const [key, value] of formData.entries()) {
        console.log(`${key}: ${value}`);
    }
    
    // 直接获取值
    const name = formData.get("username");
    const files = formData.getAll("files");
    console.log("用户名:", name);

    // 方式2:手动取值
    const email = form.querySelector('[name="email"]').value;
    const password = form.querySelector('[name="password"]').value;

    // 转为普通对象
    const data = Object.fromEntries(formData.entries());
    console.log("提交数据:", data);

    // 发送请求
    // fetch("/api/submit", {
    //     method: "POST",
    //     body: formData,  // 或 JSON.stringify(data)
    // });
});

// ========== 表单验证 ==========
const emailInput = document.querySelector('[type="email"]');
const errorSpan = document.querySelector(".error-message");

emailInput.addEventListener("input", () => {
    const value = emailInput.value;
    if (!value.includes("@")) {
        emailInput.setCustomValidity("请输入有效的邮箱地址");
        errorSpan.textContent = "邮箱格式不正确";
    } else {
        emailInput.setCustomValidity("");
        errorSpan.textContent = "";
    }
});

// 使用约束验证API
emailInput.addEventListener("blur", () => {
    console.log("validity:", emailInput.validity);
    // validity.valid, validity.valueMissing, validity.typeMismatch, ...
    console.log("验证消息:", emailInput.validationMessage);
});

7.4 BOM(浏览器对象模型)

JAVASCRIPT
// ========== window 对象 ==========
// window 是全局对象,所有全局变量和函数都是其属性

// 窗口尺寸
console.log("内宽:", window.innerWidth);
console.log("内高:", window.innerHeight);
console.log("外宽:", window.outerWidth);   // 含浏览器边框

// 滚动
window.scrollTo({ top: 0, behavior: "smooth" });
console.log("滚动X:", window.scrollX, "滚动Y:", window.scrollY);

// 打开/关闭窗口
// const newWin = window.open("https://example.com", "_blank", "width=800,height=600");
// newWin.close();

// 对话框
// alert("警告消息");
// const confirmed = confirm("确定要删除吗?");
// const name = prompt("请输入你的名字", "默认值");

// ========== location 对象 ==========
console.log("完整URL:", location.href);
console.log("路径:", location.pathname);
console.log("查询参数:", location.search);
console.log("锚点:", location.hash);
console.log("主机:", location.host);
console.log("协议:", location.protocol);

// 导航
// location.href = "https://example.com";
// location.assign("https://example.com");    // 可返回
// location.replace("https://example.com");   // 不可返回
// location.reload();

// 解析查询参数
const params = new URLSearchParams(location.search);
console.log(params.get("page"));  // 获取单个参数

// ========== history 对象 ==========
// history.back();
// history.forward();
// history.go(-1);

// HTML5 History API(SPA路由基础)
// history.pushState({ page: 1 }, "Title", "/page1");     // 添加历史记录
// history.replaceState({ page: 2 }, "Title", "/page2");   // 替换当前记录

// window.addEventListener("popstate", (e) => {
//     console.log("历史记录变化:", e.state);
// });

// ========== navigator 对象 ==========
console.log("用户代理:", navigator.userAgent);
console.log("语言:", navigator.language);
console.log("在线状态:", navigator.onLine);
console.log("Cookie启用:", navigator.cookieEnabled);

// ========== screen 对象 ==========
console.log("屏幕宽:", screen.width, "高:", screen.height);
console.log("可用宽:", screen.availWidth, "高:", screen.availHeight);

7.5 Web Storage

JAVASCRIPT
// ========== localStorage:持久存储(不过期)==========
// 存储字符串
localStorage.setItem("username", "Alice");
localStorage.setItem("settings", JSON.stringify({ theme: "dark", lang: "zh" }));

// 读取
const username = localStorage.getItem("username");
const settings = JSON.parse(localStorage.getItem("settings"));

// 删除
localStorage.removeItem("username");
// localStorage.clear();  // 清空所有

// 遍历
for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    console.log(`${key}: ${localStorage.getItem(key)}`);
}

// ========== sessionStorage:会话存储(标签页关闭后清除)==========
sessionStorage.setItem("temp", "临时数据");
// API 与 localStorage 完全相同

// ========== Cookie ==========
// 设置Cookie
document.cookie = "username=Alice; max-age=3600; path=/; secure; samesite=lax";

// 读取Cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(";").shift();
    return null;
}

// 删除Cookie(设置过期时间为过去)
document.cookie = "username=; max-age=0";

// ========== IndexedDB(大型结构化数据存储)==========
const request = indexedDB.open("MyDatabase", 1);

request.onupgradeneeded = (event) => {
    const db = event.target.result;
    const store = db.createObjectStore("users", { keyPath: "id" });
    store.createIndex("name", "name", { unique: false });
};

request.onsuccess = (event) => {
    const db = event.target.result;
    const tx = db.transaction("users", "readwrite");
    const store = tx.objectStore("users");
    
    store.add({ id: 1, name: "Alice", age: 25 });
    store.get(1).onsuccess = (e) => console.log("读取:", e.target.result);
};

八、模块化

8.1 ES6 模块

JAVASCRIPT
// ========== 导出(export)==========
// math.js

// 命名导出(可多个)
export const PI = 3.14159;

export function add(a, b) {
    return a + b;
}

export class Calculator {
    multiply(a, b) { return a * b; }
}

// 批量导出
const subtract = (a, b) => a - b;
const divide = (a, b) => a / b;
export { subtract, divide };

// 默认导出(每个模块只能有一个)
export default function greet(name) {
    return `Hello, ${name}!`;
}

// 重命名导出
export { subtract as minus };

// ========== 导入(import)==========
// app.js

// 命名导入
import { PI, add, Calculator } from "./math.js";

// 默认导入
import greet from "./math.js";

// 混合导入
import greetDefault, { PI, add } from "./math.js";

// 重命名导入
import { add as sum } from "./math.js";

// 整体导入(命名空间)
import * as math from "./math.js";
console.log(math.PI, math.add(1, 2));

// 仅执行模块(不导入任何内容)
import "./init.js";

// ========== 动态导入(import())= 返回Promise)==========
// 可用于条件加载、按需加载、代码分割
async function loadModule(moduleName) {
    try {
        const module = await import(`./modules/${moduleName}.js`);
        module.default();
    } catch (err) {
        console.error("模块加载失败:", err);
    }
}

// 条件导入
if (condition) {
    import("./feature.js").then(m => m.init());
}

// ========== import.meta ==========
console.log(import.meta.url);      // 当前模块的URL
// console.log(import.meta.resolve); // 解析模块路径

8.2 CommonJS 模块(Node.js)

JAVASCRIPT
// ========== 导出 ==========
// math.cjs

const PI = 3.14159;

function add(a, b) {
    return a + b;
}

// 方式1:module.exports
module.exports = {
    PI,
    add,
};

// 方式2:逐个导出(不推荐混用)
// exports.PI = PI;
// exports.add = add;

// ========== 导入 ==========
// app.cjs

// 直接导入
const math = require("./math.cjs");
console.log(math.PI, math.add(1, 2));

// 解构导入
const { PI, add } = require("./math.cjs");

// 动态 require
if (condition) {
    const feature = require("./feature.cjs");
}

// ========== ES模块与CommonJS互操作 ==========
// 在ES模块中导入CommonJS模块
// import cjsModule from "./math.cjs";   // Node.js支持
// import { PI } from "./math.cjs";       // 可能不支持命名导入

// 在CommonJS中导入ES模块
// const esModule = await import("./math.js");  // 异步动态导入

九、Node.js核心API

9.1 fs模块:文件系统

JAVASCRIPT
const fs = require("fs");
const fsPromises = require("fs/promises");
const path = require("path");

// ========== 同步读取(阻塞,仅用于启动脚本)==========
const data = fs.readFileSync("file.txt", "utf8");
console.log(data);

// ========== 异步读取(回调方式)==========
fs.readFile("file.txt", "utf8", (err, data) => {
    if (err) {
        console.error("读取失败:", err);
        return;
    }
    console.log(data);
});

// ========== Promise方式(推荐)==========
async function readConfig() {
    try {
        const data = await fsPromises.readFile("config.json", "utf8");
        return JSON.parse(data);
    } catch (err) {
        console.error("读取配置失败:", err);
        return {};
    }
}

// ========== 写入文件 ==========
// 同步
fs.writeFileSync("output.txt", "Hello, Node.js!\n", { flag: "a" });

// 异步Promise
await fsPromises.writeFile("output.txt", "Hello!\n", { flag: "a" });

// 追加
await fsPromises.appendFile("output.txt", "追加的内容\n");

// ========== 流式读写(处理大文件)==========
const readStream = fs.createReadStream("largeFile.txt", { highWaterMark: 64 * 1024 });
const writeStream = fs.createWriteStream("copy.txt");

readStream.pipe(writeStream);
// 或
readStream.on("data", (chunk) => {
    writeStream.write(chunk);
});
readStream.on("end", () => {
    writeStream.end();
    console.log("复制完成");
});

// ========== 目录操作 ==========
// 创建目录
fs.mkdirSync("newDir", { recursive: true });
await fsPromises.mkdir("newDir", { recursive: true });

// 读取目录
const files = await fsPromises.readdir(".");
console.log("文件列表:", files);

// 检查文件存在(推荐方式:直接尝试操作)
try {
    await fsPromises.access("file.txt", fs.constants.R_OK);
    console.log("文件存在且可读");
} catch {
    console.log("文件不存在或无权限");
}

// 文件信息
const stats = await fsPromises.stat("file.txt");
console.log("大小:", stats.size, "字节");
console.log("是文件:", stats.isFile());
console.log("是目录:", stats.isDirectory());
console.log("修改时间:", stats.mtime);

// 监听文件变化
fs.watch("file.txt", (eventType, filename) => {
    console.log(`文件变化: ${eventType}, ${filename}`);
});

9.2 http模块:HTTP服务器

JAVASCRIPT
const http = require("http");
const url = require("url");

// ========== 创建HTTP服务器 ==========
const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;
    const method = req.method;

    // 设置响应头
    res.setHeader("Content-Type", "application/json; charset=utf-8");
    
    // CORS 头
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    
    if (method === "OPTIONS") {
        res.writeHead(204);
        res.end();
        return;
    }

    // 路由处理
    if (pathname === "/api/users" && method === "GET") {
        res.writeHead(200);
        res.end(JSON.stringify({ 
            users: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] 
        }));
        return;
    }

    if (pathname === "/api/users" && method === "POST") {
        let body = "";
        req.on("data", chunk => body += chunk);
        req.on("end", () => {
            try {
                const user = JSON.parse(body);
                res.writeHead(201);
                res.end(JSON.stringify({ id: Date.now(), ...user }));
            } catch (err) {
                res.writeHead(400);
                res.end(JSON.stringify({ error: "无效的JSON" }));
            }
        });
        return;
    }

    // 404
    res.writeHead(404);
    res.end(JSON.stringify({ error: "未找到" }));
});

// 启动服务器
server.listen(3000, () => {
    console.log("服务器运行在 http://localhost:3000");
});

// ========== HTTP客户端请求 ==========
function httpGet(url) {
    return new Promise((resolve, reject) => {
        http.get(url, (res) => {
            let data = "";
            res.on("data", chunk => data += chunk);
            res.on("end", () => {
                try {
                    resolve(JSON.parse(data));
                } catch {
                    resolve(data);
                }
            });
        }).on("error", reject);
    });
}

// 使用
const data = await httpGet("http://jsonplaceholder.typicode.com/posts/1");
console.log(data);

9.3 其他常用Node.js模块

JAVASCRIPT
// ========== path 模块 ==========
const path = require("path");

console.log(path.join("/users", "docs", "file.txt"));  // "/users/docs/file.txt"
console.log(path.resolve("file.txt"));                   // 绝对路径
console.log(path.dirname("/a/b/file.txt"));              // "/a/b"
console.log(path.basename("/a/b/file.txt"));             // "file.txt"
console.log(path.basename("/a/b/file.txt", ".txt"));     // "file"
console.log(path.extname("file.txt"));                   // ".txt"
console.log(path.parse("/a/b/file.txt"));                // {root, dir, base, ext, name}
console.log(path.relative("/a/b", "/a/b/c/d"));          // "c/d"

// ========== os 模块 ==========
const os = require("os");

console.log("平台:", os.platform());          // linux/darwin/win32
console.log("架构:", os.arch());              // x64/arm64
console.log("CPU核数:", os.cpus().length);
console.log("总内存:", os.totalmem() / 1024 / 1024 / 1024, "GB");
console.log("空闲内存:", os.freemem() / 1024 / 1024, "MB");
console.log("主目录:", os.homedir());
console.log("临时目录:", os.tmpdir());
console.log("运行时间:", os.uptime(), "秒");

// ========== events 模块(EventEmitter)==========
const EventEmitter = require("events");

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

// 注册监听器
myEmitter.on("event", (arg1, arg2) => {
    console.log("事件触发:", arg1, arg2);
});

myEmitter.once("once-event", () => {
    console.log("只触发一次");
});

// 触发事件
myEmitter.emit("event", "参数1", "参数2");
myEmitter.emit("once-event");
myEmitter.emit("once-event");  // 不会触发

// 移除监听器
const handler = () => console.log("处理器");
myEmitter.on("test", handler);
myEmitter.off("test", handler);
// myEmitter.removeAllListeners("event");

// ========== crypto 模块 ==========
const crypto = require("crypto");

// 哈希
const hash = crypto.createHash("sha256").update("password").digest("hex");
console.log("SHA256:", hash);

// HMAC
const hmac = crypto.createHmac("sha256", "secret").update("data").digest("hex");
console.log("HMAC:", hmac);

// 随机字节
const randomBytes = crypto.randomBytes(16).toString("hex");
console.log("随机:", randomBytes);

// UUID
const uuid = crypto.randomUUID();
console.log("UUID:", uuid);

// ========== util 模块 ==========
const util = require("util");

// promisify:将回调函数转为Promise
const readFile = util.promisify(fs.readFile);
const data = await readFile("file.txt", "utf8");

// 格式化(类似Python的repr)
console.log(util.inspect({ arr: [1, 2], obj: { a: 1 } }, { depth: null, colors: true }));

// ========== child_process 模块 ==========
const { exec, spawn } = require("child_process");

// exec:执行简单命令,缓冲输出
exec("ls -la", (err, stdout, stderr) => {
    if (err) {
        console.error("错误:", err);
        return;
    }
    console.log("输出:", stdout);
});

// spawn:流式处理,适合长时间运行的命令
const child = spawn("ls", ["-la"]);
child.stdout.on("data", (data) => console.log(`输出: ${data}`));
child.stderr.on("data", (data) => console.error(`错误: ${data}`));
child.on("close", (code) => console.log(`退出码: ${code}`));

十、常用第三方库

10.1 Express:Web框架

JAVASCRIPT
const express = require("express");
const app = express();

// 中间件
app.use(express.json());       // 解析JSON请求体
app.use(express.urlencoded({ extended: true }));  // 解析URL编码
app.use(express.static("public"));  // 静态文件

// 自定义中间件
app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();  // 必须调用next()继续处理
});

// 路由
app.get("/api/users", (req, res) => {
    const { page = 1, limit = 10 } = req.query;
    res.json({ page, limit, users: [] });
});

app.get("/api/users/:id", (req, res) => {
    const { id } = req.params;
    res.json({ id, name: `User${id}` });
});

app.post("/api/users", (req, res) => {
    const user = req.body;
    // 验证 user...
    res.status(201).json({ id: Date.now(), ...user });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: "服务器内部错误" });
});

app.listen(3000, () => console.log("Express运行在端口3000"));

10.2 Fetch API(浏览器/Node.js 18+)

JAVASCRIPT
// ========== 基本请求 ==========
// GET
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await response.json();
console.log(post);

// POST(JSON)
const newPost = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer token123",
    },
    body: JSON.stringify({
        title: "Test Post",
        body: "This is a test",
        userId: 1,
    }),
}).then(res => res.json());

// ========== 超时控制(使用AbortController)==========
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);

try {
    const response = await fetch("https://api.example.com/slow", {
        signal: controller.signal,
    });
    clearTimeout(timeout);
    const data = await response.json();
} catch (err) {
    if (err.name === "AbortError") {
        console.log("请求超时");
    }
}

// ========== 文件上传 ==========
const formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("name", "document");

await fetch("/upload", {
    method: "POST",
    body: formData,
});

// ========== 下载文件 ==========
const fileResponse = await fetch("https://example.com/file.pdf");
const blob = await fileResponse.blob();
const url = URL.createObjectURL(blob);

const a = document.createElement("a");
a.href = url;
a.download = "file.pdf";
a.click();
URL.revokeObjectURL(url);

十一、测试与调试

11.1 单元测试(Jest)

JAVASCRIPT
// math.js
function add(a, b) {
    return a + b;
}

function divide(a, b) {
    if (b === 0) throw new Error("除数不能为零");
    return a / b;
}

module.exports = { add, divide };

// math.test.js
const { add, divide } = require("./math");

// 测试分组
describe("math 模块", () => {
    describe("add", () => {
        test("两个正数相加", () => {
            expect(add(2, 3)).toBe(5);
        });

        test("负数相加", () => {
            expect(add(-1, -1)).toBe(-2);
        });

        test("正负相加", () => {
            expect(add(-1, 1)).toBe(0);
        });
    });

    describe("divide", () => {
        test("正常除法", () => {
            expect(divide(10, 2)).toBe(5);
        });

        test("浮点数结果", () => {
            expect(divide(10, 3)).toBeCloseTo(3.333, 2);
        });

        test("除零抛出错误", () => {
            expect(() => divide(10, 0)).toThrow("除数不能为零");
        });
    });

    // 参数化测试
    test.each([
        [2, 3, 5],
        [0, 0, 0],
        [-1, 1, 0],
        [100, 200, 300],
    ])("add(%i, %i) = %i", (a, b, expected) => {
        expect(add(a, b)).toBe(expected);
    });
});

// 异步测试
test("异步请求测试", async () => {
    const data = await fetchData(1);
    expect(data).toHaveProperty("id");
    expect(data.name).toBeDefined();
});

// Mock
test("mock函数", () => {
    const mockFn = jest.fn();
    mockFn.mockReturnValue(42);
    expect(mockFn()).toBe(42);
    expect(mockFn).toHaveBeenCalledTimes(1);
});

// Setup/Teardown
beforeAll(() => console.log("所有测试前"));
afterAll(() => console.log("所有测试后"));
beforeEach(() => console.log("每个测试前"));
afterEach(() => console.log("每个测试后"));

11.2 调试技巧

JAVASCRIPT
// ========== console 进阶 ==========
console.log("普通日志");
console.info("信息");
console.warn("警告");
console.error("错误");
console.debug("调试");

// 分组
console.group("用户信息");
console.log("姓名: Alice");
console.log("年龄: 25");
console.groupEnd();

// 表格
console.table([
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
]);

// 计时
console.time("operation");
// ... 操作 ...
console.timeEnd("operation");  // operation: 123.456ms

// 断言
console.assert(1 === 2, "断言失败");  // 仅当条件为false时输出

// ========== 浏览器调试 ==========
// debugger:代码执行到这里会暂停
function complexOperation(data) {
    debugger;  // 浏览器DevTools会在此暂停
    return data.map(x => x * 2);
}

// ========== Node.js调试 ==========
// node --inspect app.js          # 使用Chrome DevTools调试
// node --inspect-brk app.js      # 首行暂停
// node inspect app.js            # 命令行调试器

十二、性能优化

12.1 核心优化策略

JAVASCRIPT
// ========== 防抖(Debounce)==========
// 连续触发只执行最后一次
function debounce(fn, delay = 300) {
    let timer;
    return function(...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

// 使用:搜索输入框
const searchInput = document.querySelector("#search");
searchInput.addEventListener("input", debounce((e) => {
    console.log("搜索:", e.target.value);
}, 500));

// ========== 节流(Throttle)==========
// 固定时间内只执行一次
function throttle(fn, limit = 300) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            fn.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 使用:滚动事件
window.addEventListener("scroll", throttle(() => {
    console.log("滚动位置:", window.scrollY);
}, 100));

// ========== 记忆化(Memoization)==========
function memoize(fn) {
    const cache = new Map();
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        const result = fn.apply(this, args);
        cache.set(key, result);
        return result;
    };
}

const expensiveCalc = memoize((n) => {
    console.log("计算中...");
    return n * n;
});

console.log(expensiveCalc(42));  // "计算中..." 1764
console.log(expensiveCalc(42));  // 1764(来自缓存)

// ========== 虚拟滚动(Virtual Scroll)==========
// 只渲染可见区域的数据
class VirtualScroll {
    constructor({ itemHeight, containerHeight, totalItems, renderItem }) {
        this.itemHeight = itemHeight;
        this.containerHeight = containerHeight;
        this.totalItems = totalItems;
        this.renderItem = renderItem;
        this.visibleCount = Math.ceil(containerHeight / itemHeight) + 2;
    }

    render(scrollTop) {
        const startIndex = Math.floor(scrollTop / this.itemHeight);
        const endIndex = Math.min(startIndex + this.visibleCount, this.totalItems);
        const items = [];
        for (let i = startIndex; i < endIndex; i++) {
            items.push(this.renderItem(i));
        }
        return items;
    }
}

// ========== Web Worker ==========
// 在后台线程执行耗时计算
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ data: [1, 2, 3, 4, 5] });
worker.onmessage = (e) => {
    console.log("计算结果:", e.data);
};

// worker.js
self.onmessage = (e) => {
    const result = e.data.data.reduce((sum, n) => sum + n, 0);
    self.postMessage(result);
};

12.2 内存管理与垃圾回收

JAVASCRIPT
// ========== 常见内存泄漏 ==========

// 1. 未清理的定时器
let timer = setInterval(() => {}, 1000);
// 清理:clearInterval(timer);

// 2. 未移除的事件监听器
// element.removeEventListener("click", handler);

// 3. 闭包中引用大对象
function createLeak() {
    const bigData = new Array(1000000);
    return function() {
        console.log(bigData.length);  // bigData 永远不会被GC
    };
}

// 4. 全局变量
// 尽量使用 let/const,避免意外创建全局变量

// 5. DOM引用
let element = document.querySelector("#myElement");
element.remove();  // 从DOM移除
// element = null; // 也需要释放JS引用

// ========== WeakMap/WeakSet 辅助GC ==========
const cache = new WeakMap();  // 键对象被销毁后,值自动被GC

十三、最佳实践与规范

13.1 代码规范

JAVASCRIPT
// ========== 命名规范 ==========
// 变量/函数:camelCase
const userName = "Alice";
function getUserById(id) { return {}; }

// 类/构造函数:PascalCase
class UserService {}
class DataProvider {}

// 常量:UPPER_SNAKE_CASE
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = "https://api.example.com";

// 私有属性/方法:_前缀(约定)或 #前缀(真正私有)
class MyClass {
    _privateMethod() {}  // 约定私有
    #trulyPrivate() {}   // ES2022真正私有
}

// 布尔值:is/has/can前缀
const isActive = true;
const hasPermission = false;
const canEdit = true;

// ========== 函数设计 ==========
// 函数参数不超过3个,超过用对象
function createUser({ name, email, age, role }) {
    // 清晰明确
}

// 纯函数(无副作用)
function add(a, b) {
    return a + b;  // 仅依赖参数,不修改外部状态
}

// ========== 条件判断优化 ==========
// 使用早期返回替代深层嵌套
function process(data) {
    if (!data) return null;
    if (!data.isValid) return null;
    if (data.type !== "target") return null;
    // 主逻辑
    return transform(data);
}

// 使用对象映射替代多层if/switch
const statusMap = {
    active: "激活",
    inactive: "未激活",
    suspended: "已暂停",
};
const statusText = statusMap[status] ?? "未知";

// ========== 异步处理 ==========
// 始终处理Promise的reject
fetchData().then(onSuccess).catch(onError);
// 或
const [err, data] = await to(fetchData());
// async函数调用记得await

13.2 安全实践

JAVASCRIPT
// ========== XSS 防护 ==========
// 永远不要使用 innerHTML 插入用户内容
// element.innerHTML = userInput;  // 危险!

// 安全方式
element.textContent = userInput;   // 纯文本

// 如需HTML,使用DOMPurify库
// import DOMPurify from "dompurify";
// element.innerHTML = DOMPurify.sanitize(userInput);

// ========== CSP(Content-Security-Policy)==========
// 通过HTTP头限制资源来源
// Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-xxx'

// ========== CSRF 防护 ==========
// 使用SameSite Cookie
// Set-Cookie: session=xxx; SameSite=Strict
// 使用CSRF Token

// ========== 敏感数据保护 ==========
// 不将敏感数据存储在localStorage(易被XSS读取)
// 密码等敏感数据不在前端存储
// HTTPS传输所有数据

13.3 常用工具链

BASH
# 包管理
npm init -y                   # 初始化项目
npm install <package>         # 安装依赖
npm install --save-dev <pkg>  # 安装开发依赖
npm update                    # 更新依赖
npm audit                      # 安全审计
npm audit fix                 # 修复安全问题

# 代码质量
npx eslint . --fix            # ESLint格式化
npx prettier . --write        # Prettier格式化
npx tsc --noEmit              # TypeScript类型检查

# 构建工具
# Vite: npm create vite@latest
# webpack: npx webpack build
# esbuild: npx esbuild src/app.js --bundle --outfile=dist/bundle.js

十四、总结

14.1 JavaScript核心优势

优势 说明
全栈统一 前后端同语言,降低切换成本
生态丰富 npm拥有最大的包管理器生态
异步驱动 天然支持异步编程模型(事件循环)
跨平台 浏览器、移动端、桌面端、服务端
动态灵活 原型链、动态类型实现多种编程范式
社区活跃 活跃的标准化进程(年度ECMAScript更新)

14.2 学习路径

CODE
基础语法 → 数据类型 → 函数进阶 → 异步编程 → DOM/BOM → 模块化
    ↓           ↓          ↓           ↓          ↓         ↓
  let/const   Array    闭包this    Promise    事件      ES模块
  类型转换     Object   箭头函数    async/await 表单      npm
  运算符       Map/Set  class      事件循环     Storage   Node.js

框架方向:
  React.js → Next.js → 状态管理 → SSR/SSG → TypeScript
  Vue.js  → Nuxt.js → Pinia    → 组合式API
  Node.js → Express → 数据库   → 认证授权 → 部署运维

14.3 推荐资源


祝你通过本书掌握JavaScript语言,成为一名优秀的全栈开发者!