Set vs Array
Set vs Array
一句话:Set元素唯一、查找是 O(1)、没有下标; 数组允许重复、有顺序和下标、includes 是 O(n)。
Array | Set | |
|---|---|---|
| 重复元素 | 允许 | 自动去重 |
| 查「在不在」 | includes O(n) | has O(1) |
| 下标访问 | arr[0] | 没有 |
| 取长度 | length | size |
map / filter | 有 | 没有,要先转数组 |
什么时候用 Set:去重、以及在循环里反复判断「见过没有」—— 后者是性能差别最大的场景, 数组的 includes 会让复杂度从 O(n) 变 O(n²)。
会追问:「Set 去重能去掉重复的对象吗?」——不能。Set 用的是SameValueZero(≈===), 两个内容一样的对象是不同的引用。 要按内容去重得自己用Map 按某个 key 存。
「NaN 呢?」—— Set 里NaN 只会存一个, 这是 SameValueZero和 === 唯一的差别。
In one line: a Set holds unique elements, checks membership in O(1), and has no indices; an array allows duplicates, has order and indices, and its includes is O(n).
Array | Set | |
|---|---|---|
| Duplicates | Allowed | Dropped automatically |
| “Is it in there?” | includes O(n) | has O(1) |
| Index access | arr[0] | None |
| Length | length | size |
map / filter | Yes | No — convert to an array first |
When to use a Set: deduping, and answering “have I seen this before?” inside a loop — the second is where the performance gap is biggest, because an array includes turns O(n) into O(n²).
Follow-up: “Can a Set dedupe identical objects?” — no. A Set uses SameValueZero (≈===), and two objects with the same contents are still two different references. To dedupe by content, key them yourself in a Map.
“What about NaN?” — a Set stores NaN only once. That is the only difference between SameValueZero and ===.