章节目录 · 8 章
JavaScript 教程 · 第 5 章
对象、数组、Map、Set 与迭代
JavaScript 的核心数据容器:对象用键值对组织数据,数组存储有序集合,Map / Set 是更现代的替代品。本章会把它们一网打尽,涵盖:
- 对象的创建、解构、复制、遍历
- 数组方法的完整速查与
reduce高级用法 - Set 去重、Map 任意键类型
- 迭代器协议与
for...of的本质 - 可选链
?./ 空值合并??(上一章提过,这里再完整巩固)
一、对象:键值对容器
创建对象
// 方式 1:对象字面量(最常用)
const site = {
name: "黄帝的博客",
year: 2026,
tags: ["技术", "笔记"],
getDescription() { // 方法简写
return `${this.name} · 建于 ${this.year}`;
}
};
// 方式 2:new Object()(几乎不用)
const empty = new Object();
// 方式 3:Object.create()(指定原型)
const parent = { x: 1 };
const child = Object.create(parent);
console.log(child.x); // 1 ← 从原型继承
读写属性
const user = { name: "黄帝", level: 5 };
// 点语法:键名必须是合法标识符
user.name; // "黄帝"
user.level = 6; // 修改
// 方括号:键名可以是变量、字符串、含特殊字符
const key = "name";
user[key]; // "黄帝"
user["display-name"] = "皇帝"; // 键名有短横线只能用方括号
// 计算属性名(ES6)
const prefix = "post";
const obj = {
[prefix + "Id"]: 42, // postId: 42
[`${prefix}Count`]: 10 // postCount: 10
};
// 删除属性
delete user.level;
// 检查属性是否存在
"name" in user; // true ← 包括原型链
user.hasOwnProperty("name"); // true ← 只检查自身
原型链与 proto
每个对象都有一个 __proto__ 属性,指向它的"父亲"(原型)。当访问一个不存在的属性时,JS 会沿着原型链往上找:
const arr = [1, 2, 3];
arr.length; // 直接在 arr 上
arr.push(4); // arr 上没有 → 找 Array.prototype → 找到了
arr.toString(); // arr 没有 → Array.prototype 没有 → Object.prototype 有
// 原型链末端是 null
Object.prototype.__proto__; // null
现代项目里不直接操作 __proto__,改用 Object.getPrototypeOf() / Object.setPrototypeOf()。
二、解构:快速拆包
对象解构
const user = { id: 1, name: "黄帝", level: 5, email: "huangdi@example.com" };
// 基本解构
const { name, level } = user;
console.log(name, level); // 黄帝 5
// 重命名 + 默认值
const { name: author = "匿名", level: lv = 1 } = user;
console.log(author, lv); // 黄帝 5
// 默认值生效的条件:原属性是 undefined(不是 null)
const { nickname = "无昵称" } = user; // user 没有 nickname → "无昵称"
const { id: userId = 99 } = user; // user.id = 1,不是 undefined → 1
// 嵌套解构
const response = {
data: {
user: { name: "黄帝", posts: 7, profile: { avatar: "pic.png" } }
},
status: 200
};
const {
data: {
user: { name: uName, posts, profile: { avatar } }
},
status
} = response;
console.log(uName, posts, avatar, status); // 黄帝 7 pic.png 200
// 与剩余参数搭配:挑出一部分,剩下的收入 rest
const { name, email, ...rest } = user;
console.log(name); // 黄帝
console.log(rest); // { id: 1, level: 5 }
数组解构
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3,4,5]
// 跳过某些元素
const [a, , c] = [1, 2, 3];
console.log(a, c); // 1 3
// 交换变量(一行搞定)
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
// 配合默认值
const [head = 0] = [];
console.log(head); // 0
// 字符串也能解构(因为字符串是可迭代的)
const [a1, b1, c1] = "abc";
console.log(a1, b1, c1); // a b c
三、扩展运算符 ...
扩展运算符能把数组或对象展开成单独的值,也能把多个值收集起来:
对象扩展(浅拷贝 + 合并)
// 复制对象(浅拷贝)
const config = { port: 3000, host: "localhost" };
const copy = { ...config };
copy.port = 8080;
console.log(config.port); // 3000 ← 原对象没变
// 合并对象,后者覆盖前者
const defaultOptions = { timeout: 3000, retries: 3, debug: false };
const userOptions = { timeout: 5000 };
const final = { ...defaultOptions, ...userOptions };
// { timeout: 5000, retries: 3, debug: false }
// 也可以放前面(先写默认,再用用户值覆盖)
const final2 = { ...defaultOptions, ...userOptions };
数组扩展
const arr1 = [1, 2];
const arr2 = [3, 4];
// 拼接数组
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
const extended = [...arr1, 2.5, ...arr2]; // [1, 2, 2.5, 3, 4]
// 复制数组
const copy = [...arr1];
// 把数组转成函数参数
const nums = [1, 2, 3, 4, 5];
console.log(Math.max(...nums)); // 5 ← 等价于 Math.max(1, 2, 3, 4, 5)
// 字符串转数组
const chars = [..."hello"]; // ["h","e","l","l","o"]
浅拷贝 vs 深拷贝
const original = {
name: "配置",
nested: { value: 1 },
list: [1, 2, 3]
};
// 浅拷贝:只复制第一层
const shallow = { ...original };
shallow.nested.value = 99;
console.log(original.nested.value); // 99 ← 原对象也变了!
shallow.list.push(4);
console.log(original.list); // [1,2,3,4] ← 原数组也变了
// 深拷贝:真正独立的副本
// 方法 1:JSON(只能处理纯数据,不能处理函数/undefined/Date/循环引用)
const deep1 = JSON.parse(JSON.stringify(original));
// 方法 2:structuredClone(现代浏览器和 Node 17+ 原生支持,推荐)
const deep2 = structuredClone(original);
// 方法 3:递归手写
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj);
if (Array.isArray(obj)) return obj.map(deepClone);
const result = {};
for (const key of Object.keys(obj)) {
result[key] = deepClone(obj[key]);
}
return result;
}
四、数组方法完整速查
分类一览
| 类别 | 方法 | 是否修改原数组 |
|---|---|---|
| 返回新数组 | map, filter, flat, flatMap, slice, concat, with, toSorted, toReversed, toSpliced | ❌ |
| 归约成单值 | reduce, reduceRight | ❌ |
| 查找/判断 | find, findIndex, findLast, findLastIndex, some, every, includes, indexOf, lastIndexOf | ❌ |
| 遍历 | forEach | ❌ |
| 修改原数组 | sort, reverse, splice, push, pop, shift, unshift, fill | ✅ |
| 转换 | join, toString | ❌ |
map:一一映射
const nums = [1, 2, 3, 4, 5];
// 每个元素变成两倍
const doubled = nums.map(n => n * 2);
// [2, 4, 6, 8, 10]
// 数组元素是对象时做字段变换
const users = [
{ name: "小明", age: 20 },
{ name: "小王", age: 30 }
];
const names = users.map(u => u.name);
// ["小明", "小王"]
// map 的回调接收三个参数:元素、索引、原数组
nums.map((n, i, arr) => `${i}:${n}/${arr.length}`);
// ["0:1/5", "1:2/5", "2:3/5", "3:4/5", "4:5/5"]
filter:筛选
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 偶数
const evens = nums.filter(n => n % 2 === 0);
// [2, 4, 6, 8, 10]
// 大于 5
const gt5 = nums.filter(n => n > 5);
// [6, 7, 8, 9, 10]
// 只保留真值(去掉 null/undefined/0/""/false)
const mixed = [0, "hello", null, undefined, 42, "", true];
const truthy = mixed.filter(Boolean);
// ["hello", 42, true]
flat / flatMap:打平嵌套数组
const nested = [1, [2, 3], [4, [5, [6]]]];
nested.flat(); // [1, 2, 3, 4, [5, [6]]] ← 默认打平 1 层
nested.flat(2); // [1, 2, 3, 4, 5, [6]] ← 打平 2 层
nested.flat(Infinity);// [1, 2, 3, 4, 5, 6] ← 全部打平
// flatMap:先 map 再 flat(1)
const words = ["hello world", "foo bar"];
const letters = words.flatMap(w => w.split(" "));
// ["hello", "world", "foo", "bar"]
// 等价于 words.map(w => w.split(" ")).flat()
reduce:全能归约
reduce 是数组方法里能力最强的,可以实现 map、filter、groupBy、求和、找最大最小等几乎所有操作。
// 基本形式:arr.reduce((累积值, 当前元素, 索引, 原数组) => 新累积值, 初始值)
const nums = [1, 2, 3, 4, 5];
// 求和
const sum = nums.reduce((acc, n) => acc + n, 0); // 15
// 乘积
const product = nums.reduce((acc, n) => acc * n, 1); // 120
// 找最大值
const max = nums.reduce((m, n) => Math.max(m, n), -Infinity); // 5
// 计数(等价于 filter 的长度)
const evenCount = nums.reduce((count, n) => count + (n % 2 === 0 ? 1 : 0), 0); // 2
// 分组
const users = [
{ name: "小明", dept: "前端" },
{ name: "小王", dept: "后端" },
{ name: "小李", dept: "前端" },
{ name: "小张", dept: "后端" }
];
const grouped = users.reduce((acc, u) => {
(acc[u.dept] ||= []).push(u.name);
return acc;
}, {});
// { 前端: ["小明", "小李"], 后端: ["小王", "小张"] }
// 扁平对象的 deep clone(递归)
// 之前深拷贝里用过 reduce 的版本,reduce 能做的事真的太多了
// 实现 map
const myMap = (arr, fn) => arr.reduce((acc, x, i, a) => [...acc, fn(x, i, a)], []);
// 实现 filter
const myFilter = (arr, pred) => arr.reduce((acc, x, i, a) => pred(x, i, a) ? [...acc, x] : acc, []);
查找类
const users = [
{ id: 1, name: "黄帝", active: true },
{ id: 2, name: "小明", active: false },
{ id: 3, name: "小王", active: true }
];
users.find(u => u.id === 2); // { id: 2, name: "小明", active: false } ← 返回元素,找不到 undefined
users.findIndex(u => u.id === 2); // 1 ← 返回下标,找不到 -1
users.findLast(u => u.active); // { id: 3, name: "小王", active: true } ← 从后往前找
users.some(u => !u.active); // true ← 至少有一个符合
users.every(u => u.active); // false ← 全部符合吗
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].indexOf(2); // 1(第一次出现的位置)
[1, 2, 2, 3].lastIndexOf(2); // 2(最后一次)
sort:数字排序必须传比较函数
const nums = [3, 1, 4, 1, 5, 9];
// ❌ 默认按字符串排序:"1", "1", "3", "4", "5", "9"
[...nums].sort();
// [1, 1, 3, 4, 5, 9] ← 这次碰巧对,但下面就错了
[...[10, 2, 1, 20]].sort();
// [1, 10, 2, 20] ← 字符串排序:"1" < "10" < "2" < "20"
// ✅ 数字排序:传比较函数
[...nums].sort((a, b) => a - b); // 升序 [1, 1, 3, 4, 5, 9]
[...nums].sort((a, b) => b - a); // 降序 [9, 5, 4, 3, 1, 1]
// 对象按字段排序
const users = [
{ name: "小明", age: 20 },
{ name: "小王", age: 30 },
{ name: "小李", age: 25 }
];
[...users].sort((a, b) => a.age - b.age);
// 按年龄升序
// 字符串排序用 localeCompare(支持中文排序)
[..."黄帝小明小王".split("")].sort((a, b) => a.localeCompare(b, "zh"));
// 修改原数组的 sort 一定要先复制!
const original = [3, 1, 2];
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 2] ← 原数组没变
// ES2023 新增:不修改原数组的 toSorted / toReversed / toSpliced
const sorted2 = original.toSorted((a, b) => a - b);
splice:数组的瑞士军刀
splice(start, deleteCount, ...items) 从 start 位置开始,删除 deleteCount 个元素,再在那里插入 items,返回被删除的元素数组。
const arr = ["a", "b", "c", "d", "e"];
// 删除 b、c(从下标 1 开始,删 2 个)
const removed = arr.splice(1, 2);
console.log(removed); // ["b", "c"]
console.log(arr); // ["a", "d", "e"]
// 替换:删除 0 个,插入新元素(插入)
arr.splice(1, 0, "x", "y");
console.log(arr); // ["a", "x", "y", "d", "e"]
// 删除最后一个(等价于 pop)
arr.splice(arr.length - 1, 1);
其他高频方法
const arr = [1, 2, 3, 4, 5];
arr.join("-"); // "1-2-3-4-5" ← 数组转字符串
arr.slice(1, 4); // [2, 3, 4] ← 截取子数组,不修改原数组
arr.slice(-2); // [4, 5] ← 支持负数索引,从末尾算
arr.push(6); // 末尾加,返回新长度
arr.pop(); // 末尾删,返回被删元素
arr.unshift(0); // 开头加
arr.shift(); // 开头删
arr.fill(0); // 用 0 填满整个数组
arr.fill(0, 2, 4); // 下标 2~4 填 0
arr.reverse(); // 翻转(修改原数组)
[..."hello"].reverse().join(""); // "olleh"
五、Set 与 Map
Set:自动去重的值集合
Set 存储不重复的值,查找速度比数组的 includes 快(O(1) vs O(n)):
// 创建
const s = new Set([1, 2, 2, 3, 3, 3]);
console.log(s); // Set(3) { 1, 2, 3 }
const s2 = new Set();
s2.add("apple").add("banana").add("apple");
console.log(s2.size); // 2
// 常用操作
s.has(2); // true
s.delete(3); // true(删掉了)
s.clear(); // 清空
// 数组去重的最快写法
const arr = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(arr)]; // [1, 2, 3]
// 遍历
for (const v of s) console.log(v);
s.forEach((v, v2, set) => console.log(v, v2 === v)); // Set 里 value 和 key 是同一个
// 交并差集
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
const union = new Set([...a, ...b]); // {1,2,3,4,5,6}
const intersection = new Set([...a].filter(x => b.has(x))); // {3,4}
const difference = new Set([...a].filter(x => !b.has(x))); // {1,2}
Map:键可以是任意类型
普通对象的键永远是字符串(或 Symbol),Map 的键可以是数字、对象、数组、甚至函数:
// 创建
const m = new Map();
m.set("name", "黄帝");
m.set(123, "数字键名"); // ✅ 对象做不到
m.set({ id: 1 }, "对象键名"); // ✅ 对象做不到
// 或者初始化时传二维数组
const m2 = new Map([
["a", 1],
["b", 2],
["c", 3]
]);
// 常用操作
m.get("name"); // "黄帝"
m.has("age"); // false
m.delete(123); // true
m.size; // Map 自带 size,不用 Object.keys(m).length
m.clear();
// 遍历(按插入顺序)
for (const [key, value] of m) {
console.log(key, "=", value);
}
m.forEach((value, key, map) => console.log(key, value));
// Object 转 Map:Object.entries
const obj = { a: 1, b: 2 };
const mapFromObj = new Map(Object.entries(obj));
// Map 转 Object(如果键都是字符串)
const objFromMap = Object.fromEntries(mapFromObj);
什么时候用 Map 而不是 Object?
| 场景 | 推荐 |
|---|---|
| 键是字符串 Symbol,不需要遍历顺序 | Object |
| 键会变、需要任意类型做键、频繁增删 | Map |
需要 size 属性 |
Map(Object 要手动算) |
| 需要插入顺序保证 | Map(Object 虽然也有,但 Map 更一致) |
| 纯数据传输(JSON) | Object(Map 不能直接 JSON 序列化) |
Set / Map 的 JSON 序列化
// Set → JSON 只能先转数组
JSON.stringify([...new Set([1, 2, 3])]); // "[1,2,3]"
// Map → JSON 先转 Object.fromEntries
const m = new Map([["a", 1], ["b", 2]]);
JSON.stringify(Object.fromEntries(m)); // '{"a":1,"b":2}'
六、迭代器协议与 for...of 的本质
前面反复提到 for...of 可以遍历很多东西,本质上这些东西都实现了可迭代协议:
// 数组、字符串、Map、Set、NodeList、arguments 都是可迭代的
for (const x of [1, 2, 3]) {} // 可迭代 ✅
for (const ch of "hello") {} // 可迭代 ✅
for (const [k, v] of new Map()) {} // 可迭代 ✅
for (const x of {}) {} // ❌ 对象不是可迭代的!
// 但 Object.keys / values / entries 返回的是数组(可迭代)
for (const k of Object.keys({ a: 1 })) {} // ✅
给自定义对象加迭代器
// 实现一个可迭代的 Range 类
class Range {
constructor(from, to) {
this.from = from;
this.to = to;
}
// Symbol.iterator 方法返回迭代器
[Symbol.iterator]() {
let current = this.from;
const end = this.to;
return {
next() {
if (current <= end) {
return { value: current++, done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
}
const range = new Range(1, 5);
for (const n of range) {
console.log(n); // 1 2 3 4 5
}
// 展开运算符也能用来迭代
console.log([...range]); // [1, 2, 3, 4, 5]
七、练习
第 1 题:用 reduce 统计频次
任务描述:给定一个数组,统计每个元素出现的次数,返回一个键值对对象。例如输入 ["苹果", "香蕉", "苹果", "橘子", "香蕉", "苹果"],返回 { "苹果": 3, "香蕉": 2, "橘子": 1 }。
💡 提示:用
reduce,初始值为{}。每遍历一个元素,把它当作 key,如果 key 已存在就 +1,不存在就设为 1。可以用(acc[item] ||= 0)先确保 key 存在。
参考答案:
function countOccurrences(arr) {
return arr.reduce((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});
}
// 测试
const fruits = ["苹果", "香蕉", "苹果", "橘子", "香蕉", "苹果"];
console.log(countOccurrences(fruits));
// { "苹果": 3, "香蕉": 2, "橘子": 1 }
// 数字数组也适用
const nums = [1, 2, 2, 3, 3, 3];
console.log(countOccurrences(nums));
// { "1": 1, "2": 2, "3": 3 } ← Object 的 key 自动转成字符串
第 2 题:compact 过滤假值
任务描述:实现 compact(arr) 函数,去掉数组中所有"假值"(false、0、""、null、undefined、NaN),返回新数组。例如 compact([0, 1, false, 2, "", 3, null, undefined, NaN, 4]) 返回 [1, 2, 3, 4]。
💡 提示:用
filter一行搞定,或者用reduce。最简单的写法是arr.filter(Boolean)——因为Boolean()对假值返回false,真值返回true。
参考答案:
// 写法 A:filter + Boolean(最简洁)
function compact(arr) {
return arr.filter(Boolean);
}
// 写法 B:reduce(等价实现)
function compact(arr) {
return arr.reduce((acc, item) => {
if (item) acc.push(item); // 进入这里的都是真值
return acc;
}, []);
}
// 测试
console.log(compact([0, 1, false, 2, "", 3, null, undefined, NaN, 4]));
// [1, 2, 3, 4]
第 3 题:Set 实现交并差集
任务描述:给定两个数组 a 和 b,分别实现三个函数:
union(a, b)— 并集(所有不重复的元素)intersection(a, b)— 交集(同时存在于两个数组的元素)difference(a, b)— 差集(在 a 中但不在 b 中的元素)
💡 提示:先把数组转成 Set 去重。并集用
new Set([...setA, ...setB]);交集用[...setA].filter(x => setB.has(x));差集用[...setA].filter(x => !setB.has(x))。最后转回数组。
参考答案:
function union(a, b) {
return [...new Set([...a, ...b])];
}
function intersection(a, b) {
const setB = new Set(b);
return [...new Set(a)].filter(x => setB.has(x));
}
function difference(a, b) {
const setB = new Set(b);
return [...new Set(a)].filter(x => !setB.has(x));
}
// 测试
const a = [1, 2, 3, 4, 4];
const b = [3, 4, 5, 6];
console.log(union(a, b)); // [1, 2, 3, 4, 5, 6]
console.log(intersection(a, b)); // [3, 4]
console.log(difference(a, b)); // [1, 2]
第 4 题:pick 挑选对象键
任务描述:实现 pick(obj, keys) 函数,从对象中挑出指定的键,返回一个只包含这些键的新对象。例如 pick({ a: 1, b: 2, c: 3, d: 4 }, ["a", "c"]) 返回 { a: 1, c: 3 }。如果某个 key 在 obj 里不存在,直接忽略。
💡 提示:用
reduce遍历keys数组,只在obj里有这个 key 时才往累积对象里塞。或者用Object.fromEntries + Object.entries + filter的函数式写法。
参考答案:
// 写法 A:reduce
function pick(obj, keys) {
return keys.reduce((acc, key) => {
if (key in obj) acc[key] = obj[key];
return acc;
}, {});
}
// 写法 B:Object.fromEntries + filter
function pick(obj, keys) {
const keySet = new Set(keys);
return Object.fromEntries(
Object.entries(obj).filter(([k]) => keySet.has(k))
);
}
// 测试
const user = { id: 1, name: "黄帝", level: 5, email: "huangdi@example.com" };
console.log(pick(user, ["name", "email"]));
// { name: "黄帝", email: "huangdi@example.com" }
console.log(pick(user, ["id", "level", "xxx"]));
// { id: 1, level: 5 } ← xxx 不存在,自动忽略
第 5 题:数组排序 + 去重
任务描述:给定一个整数数组(可能有负数和重复),写一个函数 sortUnique(arr) 返回升序排序且去重的新数组。例如 sortUnique([5, 3, 8, 3, -1, 5, 0, -1]) 返回 [-1, 0, 3, 5, 8]。要求不要修改原数组。
💡 提示:先用
[...new Set(arr)]去重,再用.sort((a, b) => a - b)升序排序。注意数字排序必须传比较函数,否则[...[10, 2]].sort()会变成[10, 2](字符串排序)。
参考答案:
function sortUnique(arr) {
return [...new Set(arr)].sort((a, b) => a - b);
}
// 测试
const nums = [5, 3, 8, 3, -1, 5, 0, -1];
console.log(sortUnique(nums)); // [-1, 0, 3, 5, 8]
console.log(nums); // 原数组不变 [5, 3, 8, 3, -1, 5, 0, -1]
第 6 题(综合实战):手写深拷贝 deepClone
任务描述:实现一个 deepClone(obj) 函数,能正确处理以下类型:
- 基本类型(number / string / boolean / null / undefined / symbol / bigint)
- 数组(递归拷贝每个元素)
- 普通对象(递归拷贝每个自有属性)
Date对象(拷贝后仍是 Date)- 正则
RegExp(拷贝后仍是 RegExp) - 处理循环引用(对象自己引用自己,不能无限递归爆栈)
💡 提示:
- 先判断
obj === null || typeof obj !== "object"→ 直接返回(基本类型)。- 用
obj instanceof Date处理日期,new Date(obj)拷贝。- 用
obj instanceof RegExp处理正则。- 循环引用用
WeakMap记录已经拷贝过的对象:每次拷贝前先查 WeakMap 里有没有,有就直接返回那个副本。
参考答案:
function deepClone(obj, seen = new WeakMap()) {
// 1. 基本类型直接返回
if (obj === null || typeof obj !== "object") return obj;
// 2. 处理循环引用:已经拷过的直接返回
if (seen.has(obj)) return seen.get(obj);
// 3. Date
if (obj instanceof Date) return new Date(obj.getTime());
// 4. RegExp
if (obj instanceof RegExp) return new RegExp(obj.source, obj.flags);
// 5. 数组 / 普通对象
const clone = Array.isArray(obj) ? [] : {};
// 先注册到 seen,防止循环引用时爆栈
seen.set(obj, clone);
for (const key of Reflect.ownKeys(obj)) { // 包括 Symbol 键
clone[key] = deepClone(obj[key], seen);
}
return clone;
}
// 测试 1:基本功能
const original = {
name: "配置",
nums: [1, 2, 3],
nested: { a: 1, b: { c: 2 } },
createdAt: new Date("2026-01-01"),
pattern: /hello/gi
};
const copy = deepClone(original);
copy.nums.push(99);
copy.nested.b.c = 999;
console.log(original.nums); // [1, 2, 3] ← 原数组没变
console.log(original.nested.b.c); // 2 ← 深层没变
console.log(copy.createdAt instanceof Date); // true
console.log(copy.pattern instanceof RegExp); // true
// 测试 2:循环引用
const cyclic = { name: "我" };
cyclic.self = cyclic; // 自己引用自己
const cyclicCopy = deepClone(cyclic);
console.log(cyclicCopy.name); // "我"
console.log(cyclicCopy.self === cyclicCopy); // true ← 正确指向自己,且没爆栈
小结
- 对象用方括号访问动态键、扩展运算符浅拷贝/合并;原型链解释了属性查找。
- 解构同时支持对象和数组,可嵌套、可重命名、可给默认值、可配剩余参数。
- 深拷贝简单场景用
JSON.parse(JSON.stringify(x)),推荐structuredClone。 - 数组方法:
- 返回新数组:
map / filter / flat / slice / concat - 归约:
reduce是最强工具,能实现几乎所有操作 - 查找:
find / findIndex / some / every - 修改原数组:
sort / splice / push / pop(sort必须传比较函数)
- 返回新数组:
- Set 去重、Map 任意键类型,都比普通数组/对象更灵活;推荐用
[...new Set(arr)]去重。 for...of遍历可迭代对象(数组/字符串/Map/Set/NodeList),普通对象要用Object.entries转。
更多JavaScript教程:https://hc8.top/html-js/index.html