In ES6, Map is a new data structure that provides features not available in native objects (such as regular JavaScript objects). Here are some key differences between Map and native objects:
-
Key Types:
-
Map: Can use any type of value (including objects or primitives) as keys.
-
Objects: Typically can only use strings or
Symbolas keys. Although modern JavaScript engines automatically convert non-string keys to strings, this can lead to key collisions and unexpected behavior.
-
-
Key Order:
-
Map: Key-value pairs are ordered, and
Mapobjects are traversed in the order of insertion. -
Objects: Before ES2015, object properties had no specific order; from ES2015 onwards, the traversal order of object properties is determined by the order in which properties are added (for string keys) and the size of integer keys, with non-integer keys ordered by creation sequence.
-
-
Size Accessibility:
-
Map: Can directly access the size using the
map.sizeproperty. -
Objects: Typically require manual calculation of the number of properties, for example, via
Object.keys(obj).length.
-
-
Performance:
-
Map: Typically provides better performance in scenarios involving frequent addition and deletion of key-value pairs. Especially when dealing with a large number of key-value pairs, Map's performance is usually more stable.
-
Objects: When used as a collection of a small number of properties, native objects can also exhibit good performance.
-
-
Default Keys:
-
Map: Does not include default keys; only explicitly inserted keys are present.
-
Objects: Properties and methods on the prototype chain can be inherited, and objects by default contain methods such as
toStringorhasOwnProperty, which can cause issues in certain scenarios.
-
-
Iteration:
-
Map: Map objects can be directly iterated, providing several iteration methods including
map.keys(),map.values(),map.entries(), andmap.forEach(). -
Objects: Object properties require using
for...inloops orObject.keys(),Object.values(),Object.entries()combined withforEachmethods for iteration.
-
-
Serialization:
-
Map: Map objects cannot be directly serialized using
JSON.stringify. -
Objects: Objects can be directly serialized into JSON strings.
-
For example, if we need a key-value pair collection to record users' unique identifiers (which could be numbers, strings, or even objects), and we want to maintain insertion order, then Map is particularly suitable for this use case. Using Map, we can implement it as follows:
javascriptlet userRoles = new Map(); let user1 = { name: "Alice" }; let user2 = { name: "Bob" }; // Add user roles userRoles.set(user1, 'admin'); userRoles.set(user2, 'editor'); // Get the size of Map console.log(userRoles.size); // 2 // Iterate user roles in insertion order for (let [user, role] of userRoles.entries()) { console.log(`${user.name}: ${role}`); }
In this example, we use objects user1 and user2 as keys, which is not possible with regular objects because object keys are converted to strings.