【发布时间】:2015-12-19 01:13:31
【问题描述】:
已经有一些关于map和weak map的问题了,像这样:What's the difference between ES6 Map and WeakMap?但是我想问一下我应该在什么情况下使用这些数据结构?或者当我偏爱一个而不是其他时我应该考虑什么?
数据结构示例来自:https://github.com/lukehoban/es6features
// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;
// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;
// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined
// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set
奖金。以上哪种数据结构会产生相同/相似的结果:let hash = object.create(null); hash[index] = something;
【问题讨论】:
-
"Bonus" 每个问题问 一个 问题。
-
Relevant question 仅在地图上。尤其是 IIFE 示例
-
……还有ECMAScript 6: what is WeakSet for?。我真的很倾向于作为副本关闭。
-
这不仅是关于 WeakSet,是关于何时偏爱他人,而不是重复它...... @Bergi