以下是示例weakMap.set()方法。
<script> 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(); </script>
输出如下: GFG
weakMap.set()是JavaScript中的内置函数, 用于为WeakMap对象设置具有特定键和值的新元素。
语法如下:
weakMap.set(key, value);
参数:它接受参数" key", 这是要设置为WeakMap对象的元素的键, 而参数" value"是要设置为WeakMap对象的元素的值。
返回值:它返回WeakMap对象。
例子:
Input: weakmap1.get(key1)
Output: lsbin
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, 'lsbin' );
weakmap1.set(key2, 'gfg' );
//Returning the set values
document.write(weakmap1.get(key1) + "<br>" );
document.write(weakmap1.get(key2));
</script>
输出如下:
lsbin
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, 'lsbin' );
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>
输出如下:
lsbin
gfg
GfG is a cse portal
12345
@#$%
1.34
支持的浏览器:
- 谷歌浏览器
- IE浏览器
- 火狐浏览器
- 苹果Safari
- 歌剧