Skip to content

设置 and 映射

集合类型 for 唯一值 and 键-值 pairs 使用任何键 类型, 不只是字符串.

你将学到

  • 设置: 集合的 唯一值
  • 映射: 键-值 pairs 哪里键 能是 任何类型
  • 添加, 检查, and 移除条目
  • Iterating 使用 for...的 and spread
  • WeakSet and WeakMap for garbage-collectable 键

概念讲解

Why Not Just Objects and Arrays?

Plain objects only allow string and Symbol keys — using an object as a key silently converts it to "[对象对象]". Arrays allow duplicates and have no fast "有这个值?" check. Set and Map (ES6) solve these gaps: Set stores unique values of any type, and Map stores key-value pairs with keys of any type, preserving insertion order.

Set

A 设置 is a collection of unique values. 添加() inserts (duplicates are ignored), 有() checks membership in O(1), 删除() removes, and 大小 gives the count. Sets are the clean way to deduplicate an array: [...新 设置(arr)]. They preserve insertion order, so iteration is predictable.

Map

A 映射 is a collection of key-value pairs. Unlike objects, keys can be numbers, objects, functions, or even NaN. 设置(键, 值), 获取(键), 有(键), 删除(键), and 大小 are the core API. Use Map when you need a dictionary with non-string keys or when you need reliable insertion-order iteration (object key order has historical quirks).

Iteration

Both Set and Map are iterable with for...的. A Map yields [键, 值] pairs. You can spread them into arrays or convert with 数组.从(). Map also provides .键(), .值(), and .条目() iterators. Neither has 映射 or 筛选 methods built in — convert to an array first or loop manually.

WeakSet and WeakMap

WeakMap and WeakSet hold weak references to keys: if the key object has no other references, it can be garbage-collected, and the entry disappears. This prevents memory leaks when associating data with DOM elements or other objects. Weak entries are not iterable and do not have 大小, because their contents can change at any time during GC. Use them for metadata attached to objects you do not own.

Choosing the Right Collection

Use an array for ordered, duplicate-allowing lists. Use a Set for uniqueness or fast membership checks. Use a plain object for string-keyed records with a known shape. Use a Map for dynamic dictionaries, non-string keys, or frequent add/remove with preserved order. Use WeakMap for private metadata on external objects.

示例代码

              // Set — deduplicate and check membership
const tags = new Set();
tags.add("js").add("web").add("js"); // duplicate ignored
console.log(tags.size); // 2
console.log(tags.has("web")); // true
tags.delete("js");
console.log([...tags]); // ["web"]

// Deduplicate an array in one line
const numbers = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(numbers)];
console.log("Unique:", unique); // [1, 2, 3, 4]

// Map — keys can be any type, even objects
const meta = new Map();
const userObj = { id: 1 };
meta.set(userObj, "admin");
meta.set("count", 42);
meta.set(100, "numeric key");
console.log(meta.get(userObj)); // "admin"
console.log(meta.get(100));    // "numeric key"
console.log(meta.size);        // 3

// Iterate a Map — yields [key, value] pairs
for (const [key, value] of meta) {
  console.log(key, "→", value);
}

// Convert Map to object (string keys only) and back
const strMap = new Map([["a", 1], ["b", 2]]);
const obj = Object.fromEntries(strMap);
console.log(obj); // { a: 1, b: 2 }
const backToMap = new Map(Object.entries(obj));

// WeakMap — metadata on DOM-like objects, GC-friendly
const privates = new WeakMap();
function setPrivate(obj, data) {
  privates.set(obj, data);
}
function getPrivate(obj) {
  return privates.get(obj);
}
const widget = {};
setPrivate(widget, { state: "hidden" });
console.log(getPrivate(widget)); // { state: "hidden" }
            

Shows 设置 deduplication and membership, 映射使用对象 and numeric 键, 映射 iteration, conversion 之间映射 and 对象使用 fromEntries/条目, and WeakMap for 私有 metadata.

动手试一试

  • 行 Deduplicator

    Deduplication 是 canonical 设置 use 情况 — 动手试一试 on 文本行.

  • JSON Formatter

    Inspect 数据你 存储 in 映射 and 设置.

常见错误

错误写法

Using plain 对象 as 映射键 and 获取 '[对象对象]'

正确做法

对象键 是 coerced 到字符串, 所以 two 不同对象 become 相同键 '[对象对象]'. Use 映射当 你需要对象, 数字, or other 非-字符串键.

错误写法

Expecting 设置 and 映射到 有映射 and 筛选方法

正确做法

设置 and 映射是 iterable 但做 不有 映射/筛选/reduce. Convert 到数组首先: [...设置].映射(fn), or use 数组.从(映射, fn). 你能 也循环使用 for...的 and 构建新 集合 manually.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误