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

2021年5月2日18:33:43 发表评论 737 次浏览

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

<script> function gfg() { const weakmap = new WeakMap(); const key = {}; weakmap.set(key, 'gfg' ); document.write(weakmap.has(key)); } gfg(); </script>

输出如下: true

weakMap.has()是JavaScript中的内置函数, 用于返回布尔值, 该布尔值指示在弱映射对象中是否存在具有特定键的元素。

语法如下:

weakMap.has(key);

参数:它接受参数" key", 该参数是要测试的对象弱映射中是否存在的元素的键。

返回值:如果弱映射对象中存在具有指定键的元素, 则返回true, 否则返回false。

例子:

Input: weakmap1.has(key1)
Output: true

JavaScript, 显示此功能的工作原理:

代码1:

<script>
  
    //Creating a WeakMap() object
    const weakmap1 = new WeakMap();
     
    //Creating a key "key1"
    const key1 = {};
     
    //setting element 'gfg' to the key "key1"
    weakmap1.set(key1, 'gfg' );
     
    //Testing whether the key is present 
    //in the weakMap() object or not
    document.write(weakmap1.has(key1));
  
</script>

输出如下:

true

代码2:

<script>
  
    //Creating a WeakMap() object
    const weakmap1 = new WeakMap();
     
    //Creating a key "key1"
    const key1 = {};
     
    //Testing whether the key is present 
    //in the weakMap() object or not
    document.write(weakmap1.has(key1));
  
</script>

输出如下:

false

这里的输出为false, 因为尚未在weakMap对象的末尾设置键" key1"。

支持的浏览器:

  • 谷歌浏览器
  • IE浏览器
  • 火狐浏览器
  • 苹果Safari
  • 歌剧

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: