當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Javascript weakSet.add()用法及代碼示例


weakSet.add()是JavaScript中的內置函數,用於在對象WeakSet的末尾添加一個對象。 WeakSet對象使您可以將弱保存的對象存儲在集合中。

用法:

weakSet.add(A);

參數:它接受參數“A”,這是一個將添加到弱對象的值。
返回值:它返回弱化對象。

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()對象的末尾。



相關用法


注:本文由純淨天空篩選整理自ShivamKD大神的英文原創作品 JavaScript | weakSet.add() with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。