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

2021年5月2日18:36:33 发表评论 1,229 次浏览

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

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

输出如下: true

weakMap.delete()是JavaScript中的内置函数, 用于从对象WeakMap中删除特定元素。

语法如下:

weakMap.delete(key);

参数:它接受参数" key", 它是要从对象weakMap中删除的元素的键。

返回值:如果该元素已从weakMap对象中删除, 则返回true;如果该键不存在于weakMap对象中, 则返回false。

例子:

Input: weakmap1.delete(key1)
Output: true

JavaScript代码显示此功能的工作方式:

代码1:

<script>
  
    //Creating a WeakMap() object
    const weakmap1 = new WeakMap();
     
    //Creating a key "key1"
    const key1 = {};
     
    //Setting the value 6 with key1 to the
    //the end of weakMap object 
    weakmap1.set(key1, 6);
     
    //Deleting key of the element from
    //the weakMap object
    document.write(weakmap1. delete (key1));
  
</script>

输出如下:

true

此处输出为true, 表示元素的键已成功删除。

代码2:

<script>
  
    //Creating a WeakMap() object
    const weakmap1 = new WeakMap();
     
    //Creating a key "key1"
    const key1 = {};
     
    //Deleting key of the element from
    //the weakMap object
    document.write(weakmap1. delete (key1));
  
</script>

输出如下:

false

这里的输出为false, 因为尚未将具有任何值的键" key1"设置为weakMap对象的末尾。


木子山

发表评论

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