JavaScript的weakSet.add()方法用法介绍

以下是示例weakSet.add()方法。

< script> function gfg() { const weakset = new WeakSet(); const object1 = {}; weakset.add(object1); document.write(weakset.has(object1)); } gfg(); < /script>

输出如下:true
weakSet.add()是JavaScript中的内置函数, 用于在对象末尾添加对象弱集。通过WeakSet对象, 可以将弱保存的对象存储在集合中。
语法如下:
weakSet.add(A);

参数:它接受参数" A", 这是将添加到弱化对象的值。
返回值:它返回弱化对象。
例子:
Input: weakset.add(object1); Output: true

JavaScript代码显示此功能的工作方式:
代码1:
< script> //Constructing a weakset object const weakset = new WeakSet(); //Constructing a new object object1 const object1 = {}; const object2 = {}; const object3 = {}; const object4 = {}; //Adding the object1 at the end of the weakset object. weakset.add(object1); weakset.add(object2); weakset.add(object3); weakset.add(object4); //Printing either object has been added or not document.write(weakset.has(object1) + "< br> " ); document.write(weakset.has(object2) + "< br> " ); document.write(weakset.has(object3) + "< br> " ); document.write(weakset.has(object4)); < /script>

输出如下:
true true true true

代码2:
< script> //Constructing a weakset object const weakset = new WeakSet(); //Constructing a new object object1 const object1 = {}; const object2 = {}; const object3 = {}; const object4 = {}; //Printing either object has been added or not document.write(weakset.has(object1) + "< br> " ); document.write(weakset.has(object2) + "< br> " ); document.write(weakset.has(object3) + "< br> " ); document.write(weakset.has(object4)); < /script>

输出如下:
false false false false

这里的输出为false, 因为尚未将新创建的对象设置为weakSet()对象的末尾。
【JavaScript的weakSet.add()方法用法介绍】支持的浏览器:
  • 谷歌浏览器
  • IE浏览器
  • 火狐浏览器
  • 苹果Safari
  • 歌剧

    推荐阅读