当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Javascript weakMap.set()用法及代码示例


weakMap.set()是JavaScript中的内置函数,用于为WeakMap对象设置具有特定键和值的新元素。句法:

weakMap.set(key, value);

参数:它接受参数“key”,这是要设置为WeakMap对象的元素的键,而参数“value”是要设置为WeakMap对象的元素的值。
返回值:它返回WeakMap对象。

JavaScript代码显示此函数的工作方式:

代码1:
<script>  
  
    // creating WeakMap() object 
    const weakmap1 = new WeakMap(); 
      
    // Creating some keys 
    const key1 = {}; 
    const key2 = {}; 
  
    // Setting key and value to the object. 
    weakmap1.set(key1, 'GeeksForGeeks'); 
    weakmap1.set(key2, 'gfg'); 
  
   // Returning the set values 
   document.write(weakmap1.get(key1) +"<br>"); 
   document.write(weakmap1.get(key2)); 
  
</script>

输出:


GeeksForGeeks
gfg

代码2:

<script>  
  
    // creating WeakMap() object 
    const weakmap1 = new WeakMap(); 
      
    // Creating some keys 
    const key1 = {}; 
    const key2 = {}; 
    const key3 = {}; 
    const key4 = {}; 
    const key5 = {}; 
    const key6 = {}; 
  
    // Setting key and value to the object. 
    weakmap1.set(key1, 'GeeksForGeeks'); 
    weakmap1.set(key2, 'gfg'); 
    weakmap1.set(key3, 'GfG is a cse portal'); 
    weakmap1.set(key4, '12345'); 
    weakmap1.set(key5, '@#$%'); 
    weakmap1.set(key6, '1.34'); 
  
   // Returning the set values 
   document.write(weakmap1.get(key1) +"<br>"); 
   document.write(weakmap1.get(key2) +"<br>"); 
   document.write(weakmap1.get(key3) +"<br>"); 
   document.write(weakmap1.get(key4) +"<br>"); 
   document.write(weakmap1.get(key5) +"<br>"); 
   document.write(weakmap1.get(key6)); 
  
</script>

输出:

GeeksForGeeks
gfg
GfG is a cse portal
12345
@#$%
1.34


相关用法


注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 JavaScript | weakMap.set() with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。