WeakSet
WeakSet 对象允许你将弱保持对象存储在一个集合中。
语法
new WeakSet([iterable]);参数
iterable如果传入一个可迭代对象作为参数, 则该对象的所有迭代值都会被自动添加进生成的 WeakSet 对象中.
描述
WeakSet对象是一些对象值的集合, 并且其中的每个对象值都只能出现一次.
它和 Set 对象的区别有两点:
WeakSet对象中只能存放对象引用, 不能存放值, 而Set对象都可以.
WeakSet对象中存储的对象值都是被弱引用的, 如果没有其他的变量或属性引用这个对象值, 则这个对象值会被当成垃圾回收掉. 正因为这样,WeakSet对象是无法被枚举的, 没有办法拿到它包含的所有元素.
属性
WeakSet.lengthlength 属性的值为 0.
WeakSet.prototypeWeakSet 实例的所有继承属性和继承方法都在该对象上.
WeakSet 实例
所有WeakSet 实例都继承自WeakSet.prototype.
属性
WeakSet.prototype.constructor返回构造函数即WeakSet本身.
方法
WeakSet.prototype.add(value) 在该 WeakSet 对象中添加一个新元素value.
WeakSet.prototype.clear()清空该 WeakSet 对象中的所有元素.
WeakSet.prototype.delete(value)从该 WeakSet 对象中删除value 这个元素, 之后 WeakSet.prototype.has(value) 方法便会返回false.
WeakSet.prototype.has(value)返回一个布尔值, 表示给定的值value是否存在于这个 WeakSet中.
示例
例1: 使用 WeakSet
var ws = new WeakSet();
var obj = {};
var foo = {};
ws.add(window);
ws.add(obj);
ws.has(window); // true
ws.has(foo); // false, foo has not been added to the set
ws.delete(window); // removes window from the set
ws.has(window); // false, window has been removed规范
Specification | Status | Comment |
|---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'WeakSet' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'WeakSet' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
Basic support | 36 | 12 | 34 (34) | No support | 23 | 9 |
new WeakSet(iterable) | 38 | 12 | 34 (34) | No support | 25 | 9 |
Constructor argument: new WeakSet(null) | (Yes) | 12 | 37 (37) | No support | ? | 9 |
Obsolete clear() method removed | 43 | 12 | 46 (46) | No support | 30 | 9 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
Basic support | No support | (Yes) | 34.0 (34) | No support | No support | 9 |
new WeakMap(iterable) | No support | (Yes) | 34.0 (34) | No support | No support | 9 |
Constructor argument: new WeakSet(null) | ? | (Yes) | (Yes) | No support | ? | 9 |
Obsolete clear() method removed | No support | (Yes) | ? | No support | ? | 9 |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

