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


Javascript Map.get( )用法及代码示例


什么是JavaScript中的Map?

  • Map是JavaScript中的数据结构,它允许存储[键,值]对,其中任何值都可以用作键或值。
  • Map集合中的键和值可以是任何类型,并且如果使用集合中已存在的键将值添加到Map集合中,则新值将替换旧值。
  • 映射对象中元素的迭代按插入顺序完成,并且“for…”循环为每次迭代返回所有[键,值]对的数组。

JavaScript中对象与Map之间的差异
这两种数据结构在许多方面都是相似的,例如都使用键存储值,允许使用键检索这些值,删除键并验证键是否具有任何值。但是,JavaScript中的对象和Map之间存在相当大的差异,这使得在许多情况下使用Map成为更好,更可取的选择。

  • 映射中使用的键可以是任何类型的值,例如函数,对象等,而对象中的键则限于符号和字符串。
  • 通过使用size属性可以轻松知道Map的大小,但是在处理对象时,必须手动确定大小。
  • 在要求涉及频繁添加和删除[键,值]对的情况下,最好使用Map,因为map是一种迭代数据类型,可以直接进行迭代,而迭代对象需要以特定方式获取其键。

JavaScript中的Map.get()方法
JavaScript中的Map.get()方法用于返回Map中存在的所有元素之中的特定元素。
Map.get()方法将要返回的元素的键作为参数,并返回与作为参数传递的指定键相关联的元素。如果映射中不存在作为参数传递的键,则Map.get()方法将返回undefined。
应用范围:


  • Map.get()方法用于获取Map中所有元素中的特定元素。

用法:

mapObj.get(key)

Parameters Used:

  • key: It is the key of the element of the map which has to be returned.

返回值:

  • The Map.get() method returns the element which is associated with the specified key passed as an argument or undefined if the key passed as an argument is not present in the map.

下面提供上述函数的示例。

例子:

Input : var myMap = new Map();
        myMap.set(0, 'geeksforgeeks');
        document.write(myMap.get(0));

Output: "geeksforgeeks"

说明:在此示例中,已使用单个[键,值]对创建了映射对象“myMap”,并且使用Map.get()方法返回与键“ 0”关联的元素。

Input : var myMap = new Map();
        myMap.set(0, 'geeksforgeeks');
        myMap.set(1, 'is an online portal');
        myMap.set(2, 'for geeks');
        document.write(myMap.get(0),"<br>");
        document.write(myMap.get(2),"<br>");
        document.write(myMap.get(4),"<br>");

Output: "geeksforgeeks"
         "for geeks"
          undefined

说明:在此示例中,已使用三个[键,值]对创建了映射对象“myMap”,并且使用Map.get()方法返回与键“ 0”,“ 2”和“ 4”关联的元素'。当 key 传递为“ 4”时,Map.get()返回未定义,因为映射中不存在 key “ 4”。

代码1:

<script> 
    // creating a map object 
    var myMap = new Map(); 
  
// Adding [key, value] pair to the map 
myMap.set(0, 'geeksforgeeks'); 
  
// displaying the element which is associated with 
// the key '0' using Map.get() method 
document.write(myMap.get(0)); 
  
</script>

输出:

"geeksforgeeks"

代码2:

<script> 
  
    // creating a map object 
    var myMap = new Map(); 
  
// Adding [key, value] pair to the map 
myMap.set(0, 'geeksforgeeks'); 
myMap.set(1, 'is an online portal'); 
myMap.set(2, 'for geeks'); 
  
// displaying the elements which are associated with the keys '0', '2'  
// and '4' using Map.get() method 
document.write(myMap.get(0),"</br>"); 
document.write(myMap.get(2),"</br>"); 
document.write(myMap.get(4),"</br>"); 
  
</script>                    

输出:

"geeksforgeeks"
"for geeks"
undefined

异常:

  • 如果变量不是Map类型,则Map.get()操作将引发TypeError。
  • 如果Map.get()函数中指定的索引不属于Map的[键,值]对,则Map.get()函数将返回undefined。



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