除了使用MAP-像對象,出現了有一段時間的實際Map
object,編譯到ES6時,或使用與ES6 type-definitions一個填充工具時,這是在打字稿可用:
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");
此單獨擁有使用MAP- 像對象的幾個優點,如:
甲通常情況下,Map
對象爲常見任務提供了更強大和更優雅的API,但大多數API不通過簡單的Object
s就可以使用,而無需一起輔助函數(儘管其中一些需要用於ES5目標或更低級別的完整ES6迭代器/可迭代polyfill) :
// 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());
舊帖子,但請注意,有ES6映射 –