Objects and Maps
Article Directory
Comparison between Object and Map
Object: Object is the most commonly used reference type data, which can be used to store a collection of key-value pairs, added in ECMAScript 1st
Map: Map is a collection of key-value pairs, stored in a Hash structure, which is newly added in ES6
common ground
Common ground: dynamic collection of key-value pairs, support for adding and deleting key-value pairs
Object:
const obj = {
//定义
a:1,
b:2
}
obj.c = 3; //添加键值对
delete obj.c; //删除键值对
Map:
const map = new Map() //定义
map.set('a',1); //添加键值对
map.set('b',2);
map.delete('a'); //删除键值对
difference
1. Construction method
Object
1、
const obj = {
a:1,
b:2
}
2、
const a = new Object()
3、
const a = Object.create()
Map
1、
const m = new MAp()
2、
const m = new MAp([
['a','1'],
['b','2'],
])
2. Key type
Object
The key type must be String or Symbol, if it is not a String type, data type conversion will be performed
Map
The key type can be any type, including objects, arrays, functions, etc., and no type conversion will be performed
When adding a key-value pair, use strict equality (===) to determine whether the key attribute already exists
3. The order of the keys
Object
keys are unordered and will not be returned in the order they were added
1. For integers greater than or equal to 0, they will be returned in the order of addition; for decimals and negative numbers, they will be treated as strings
2. For the String type, output in the defined order, and numbers are better than strings
3. For the Symbol type, it will be filtered directly and will not be output
If you want to output, you can pass **Object.getOwnPropertySymbols()** method
Map
The keys are ordered and returned in the order of insertion
4. Key-value pair size
Object
Can only be calculated manually, through Object.keys() method or for...in loop statistics
Map
Access directly through the size attribute
5. Key-value pair access
Object
Map
6. Iterators
Object : It does not have the feature of iterator itself, and by default it cannot be traversed using for...of
Map : The keys(), values(), and entries() methods of the MAp structure return values with the iterator feature
7. JSON serialization
Object type can be serialized through **JSON.stringify()**
The Map structure cannot be serialized directly to JSON, but the map can be converted into an array through Array.from(), and then serialized through **JSON.stringify()**
Applicable scenarios of Object and Map
Object
1. Only for data storage, and the attributes are only strings or Symbols
2. It needs to be serialized and converted to json transmission
3. As an instance of an object, you need to retain your own properties and methods
Map
1. Frequently update or delete key-value pairs
2. Store a large amount of data, especially when the key type is unknown
3. Frequent iterative processing is required