在线文档教程

WeakSet

WeakSet

WeakSet 对象允许你将弱保持对象存储在一个集合中。

语法

new WeakSet([iterable]

参数

iterable如果传入一个可迭代对象作为参数, 则该对象的所有迭代值都会被自动添加进生成的 WeakSet 对象中.

描述

WeakSet对象是一些对象值的集合, 并且其中的每个对象值都只能出现一次.

它和 Set 对象的区别有两点:

  • WeakSet 对象中只能存放对象引用, 不能存放值, 而 Set 对象都可以.

  • WeakSet 对象中存储的对象值都是被弱引用的, 如果没有其他的变量或属性引用这个对象值, 则这个对象值会被当成垃圾回收掉. 正因为这样, WeakSet 对象是无法被枚举的, 没有办法拿到它包含的所有元素.

属性

WeakSet.lengthlength 属性的值为 0.

WeakSet 实例

所有WeakSet 实例都继承自WeakSet.prototype.

属性

WeakSet.prototype.constructor返回构造函数即WeakSet本身.

方法

WeakSet.prototype.add(value) 在该 WeakSet 对象中添加一个新元素value.

示例

例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

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'WeakSet' in that specification.StandardInitial definition.
ECMAScript Latest Draft (ECMA-262)The definition of 'WeakSet' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support361234 (34)No support239
new WeakSet(iterable)381234 (34)No support259
Constructor argument: new WeakSet(null)(Yes)1237 (37)No support?9
Obsolete clear() method removed431246 (46)No support309

FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic supportNo support(Yes)34.0 (34)No supportNo support9
new WeakMap(iterable)No support(Yes)34.0 (34)No supportNo support9
Constructor argument: new WeakSet(null)?(Yes)(Yes)No support?9
Obsolete clear() method removedNo support(Yes)?No support?9