📜  TypeScript映射

📅  最后修改于: 2021-01-11 12:37:40             🧑  作者: Mango

TypeScript映射

TypeScript映射是ES6版本的JavaScript中添加的新数据结构。它使我们能够以键值对的形式存储数据,并且可以像其他编程语言一样记住键的原始插入顺序。在TypeScript映射中,我们可以将任何值用作

建立地图

我们可以如下创建地图。

var map = new Map();

地图方法

下面列出了TypeScript映射方法。

SN Methods Descriptions
1. map.set(key, value) It is used to add entries in the map.
2. map.get(key) It is used to retrieve entries from the map. It returns undefined if the key does not exist in the map.
3. map.has(key) It returns true if the key is present in the map. Otherwise, it returns false.
4. map.delete(key) It is used to remove the entries by the key.
5. map.size() It is used to returns the size of the map.
6. map.clear() It removes everything from the map.

我们可以从以下示例中了解map方法。

let map = new Map();

map.set('1', 'abhishek');   
map.set(1, 'www.javatpoint.com');     
map.set(true, 'bool1'); 
map.set('2', 'ajay');

console.log( "Value1= " +map.get(1)   ); 
console.log("Value2= " + map.get('1') ); 
console.log( "Key is Present= " +map.has(3) ); 
console.log( "Size= " +map.size ); 
console.log( "Delete value= " +map.delete(1) ); 
console.log( "New Size= " +map.size );

输出:

当我们执行上述代码片段时,它将返回以下输出。

迭代地图数据

我们可以使用'for … of '循环遍历映射键,值或条目。以下示例有助于更清楚地理解它。

let ageMapping = new Map();
 
ageMapping.set("Rakesh", 40);
ageMapping.set("Abhishek", 25);
ageMapping.set("Amit", 30);
 
//Iterate over map keys
for (let key of ageMapping.keys()) {
    console.log("Map Keys= " +key);        
}
//Iterate over map values
for (let value of ageMapping.values()) {
    console.log("Map Values= " +value);    
}
console.log("The Map Enteries are: "); 
//Iterate over map entries
for (let entry of ageMapping.entries()) {
    console.log(entry[0], entry[1]); 
}

输出: