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


JavaScript weakMap set()用法及代码示例


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

用法:

weakMap.set(key, value);

参数:它采用参数“key”,它是要设置到WeakMap对象的元素的键,参数“value”是要设置到WeakMap对象的元素的值。

返回值:它返回WeakMap对象。

以下是weakMap.set()方法的示例。

示例 1:

javascript


function gfg() {  
    const weakmap1 = new WeakMap(); 
  
    const key1 = {}; 
    const key2 = {}; 
    const key3 = {}; 
  
    weakmap1.set(key1, 'G'); 
    weakmap1.set(key2, 'F'); 
    weakmap1.set(key3, 'G'); 
  
    document.write(weakmap1.get(key1)  
    +weakmap1.get(key2) 
    +weakmap1.get(key3)); 
}

输出:

GFG

示例 2:

javascript


// 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 
console.log(weakmap1.get(key1)); 
console.log(weakmap1.get(key2));

输出:

GeeksForGeeks
gfg

示例 3:

javascript


// 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 
console.log(weakmap1.get(key1)); 
console.log(weakmap1.get(key2)); 
console.log(weakmap1.get(key3)); 
console.log(weakmap1.get(key4)); 
console.log(weakmap1.get(key5)); 
console.log(weakmap1.get(key6));

输出:

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

支持的浏览器:

  • 谷歌浏览器 36 及以上版本
  • 边 12 及以上
  • 火狐浏览器 6 及以上版本
  • Internet Explorer 11 及更高版本
  • Opera 23 及以上
  • Safari 8 及以上版本

我们有 JavascriptweakMap 方法的完整列表,要检查这些方法,请阅读这篇JavaScript WeakMap Complete Reference 文章。

我们有一份关于 Javascript 的备忘单,其中涵盖了 Javascript 的所有重要主题,请查看这些主题Javascript Cheat Sheet-A JavaScript 基本指南.



相关用法


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