JavaScript weakMap.get()方法用法示例

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

< script> function gfg() { const weakmap1 = new WeakMap(); const key1 = {}; weakmap1.set(key1, 12); document.write(weakmap1.get(key1)); } gfg(); < /script>

输出如下: 12
weakMap.get()是JavaScript中的内置函数, 用于从对象WeakMap返回特定元素。
语法如下:
weakMap.get(key);

参数:它接受参数" key", 它是将从对象weakmap返回的元素的键。
返回值:它返回与WeakMap对象中的特定键关联的元素, 如果找不到该键, 则返回未定义。
例子:
Input: weakmap1.get(key1) Output: 42

JavaScript代码来显示weakmap()函数的工作方式:
代码1:
< script> //Creating a WeakMap() object const weakmap1 = new WeakMap(); //Creating a key "key1" const key1 = {}; //setting value 42 with key "key1" in the //object weakMap weakmap1.set(key1, 42); //Getting the specified elements i.e, 42 document.write(weakmap1.get(key1)); < /script>

输出如下:
42

代码2:
< script> //Creating a WeakMap() object const weakmap1 = new WeakMap(); //Creating a key "key1" const key1 = {}; //Getting the specified elements document.write(weakmap1.get(key1)); < /script>

【JavaScript weakMap.get()方法用法示例】输出如下:
undefined

此处的输出未定义, 因为尚未在weakMap对象的末尾设置键" key1"。
支持的浏览器:
  • 谷歌浏览器
  • IE浏览器
  • 火狐浏览器
  • 苹果Safari
  • 歌剧

    推荐阅读