除了使用类似map 的对象外,现在还有一个实际的Map
对象,当编译到 ES6 或使用带有 ES6类型定义的 polyfill 时,它在 TypeScript 中可用:
let people = new Map<string, Person>();
它支持与 相同的功能Object
,甚至更多,但语法略有不同:
// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });
// Checking for the presence of a key:
people.has("John"); // true
// Retrieving a value by a key:
people.get("John").lastName; // "Doe"
// Deleting an item by a key:
people.delete("John");
与使用类似地图的对象相比,仅此一项就有几个优点,例如:
- 支持非基于字符串的键,例如数字或对象,它们都不支持
Object
(不,Object
不支持数字,它将它们转换为字符串)
- 不使用时出错的空间更小
--noImplicitAny
,因为 aMap
始终具有键类型和值类型,而对象可能没有索引签名
- 添加/删除项目(键值对)的功能针对任务进行了优化,这与在
Object
此外,一个Map
对象为常见任务提供了一个更强大和优雅的 API,其中大部分在 simple Object
s 中无法使用,而无需将辅助函数组合在一起(尽管其中一些需要完整的 ES6 迭代器/可迭代的 polyfill 用于 ES5 目标或以下目标):
// Iterate over Map entries:
people.forEach((person, key) => ...);
// Clear the Map:
people.clear();
// Get Map size:
people.size;
// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());
// Extract values into array (in insertion order):
let values = Array.from(people.values());