1. Don’t treat objects as Maps1. Undefined properties may be accessed through the prototype chainAssuming the current scenario, when developing a website, we need to provide three languages: Japanese, Chinese, and Korean. We can define a dictionary to manage them. const dictionary = { 'ja': { 'Ninjas for hire': 'Ninjas for hire', }, 'zh': { 'Ninjas for hire': 'Ninjas for hire', }, 'ko': { 'Ninjas for hire': '고용닌자', } } console.log(dictionary.ja['Ninjas for hire']) // ninjas for hireconsole.log(dictionary.zh['Ninjas for hire']) // ninjas for hireconsole.log(dictionary.ko['Ninjas for hire']) // ninjas for hireconsole.log(dictionary.ko['Ninjas for hire']) // ninjas for hire In this way, we manage dictionaries in different languages. However, problems arise when we try to access console.log(dictionary.ko['constructor']) // ƒ Object() { [native code] } For non-existent properties, we expect to get One solution here is to set the prototype to Object.setPrototypeOf(dictionary.ko, null) console.log(dictionary.ko['constructor']) // undefined 2. The key of the object can only be a string Suppose you need to map /* HTML part <div id="firstElement"></div> <div id="secondElement"></div> */ const firstElement = document.getElementById('firstElement') const secondElement = document.getElementById('secondElement') const map = {} map[firstElement] = { data: 'firstElement' } map[secondElement] = { data: 'secondElement' } console.log(map[firstElement].data) // secondElement console.log(map[secondElement].data) // secondElement The data of the first element is overwritten because the key in the object can only be of string type. When we do not use the string type, it implicitly calls Object keys can also be 2. Using Map1. Common Map Operations function People(name) { this.name = name } const zhangsan = new People('zhangsan') const xiaoming = new People('xiaoming') const lihua = new People('lihua') // Create a Map const map = new Map() // Create a Map and initialize it to convert the two-dimensional key-value array into a Map object const map1 = new Map([ ['key1', 'val1'], ['key2', 'val2'], ]) // Convert Map to a two-dimensional array console.log(Array.from(map1)) // [ [ 'key1', 'val1' ], [ 'key2', 'val2' ] ] // Set the key-value mapping relationship map.set(zhangsan, { region: 'HB' }) map.set(xiaoming, { region: 'HN' }) // Get the corresponding value according to the key console.log(map.get(zhangsan)) // { region: 'HB' } console.log(map.get(xiaoming)) // { region: 'HN' } // Get the non-existent key and get undefined console.log(map.get(lihua)) // undefined // Use the has function to determine whether the specified key exists console.log(map.has(lihua)) // false console.log(map.has(xiaoming)) // true //map stores the number of mappingsconsole.log(map.size) // 2 // delete delete key map.delete(xiaoming) console.log(map.has(xiaoming)) // false console.log(map.size) // 1 // clear clears the map map.clear() console.log(map.size) // 0 2. Traversing the MapMap can ensure that the traversal order is consistent with the insertion order const zhangsan = { name: 'zhangsan' } const xiaoming = { name: 'xiaoming' } const map = new Map() map.set(zhangsan, { region: 'HB' }) map.set(xiaoming, { region: 'HN' }) // Each key-value pair returns an array of [key, value] for (let item of map) { // = for (let item of map.entries()) { console.log(item) // [ { name: 'zhangsan' }, { region: 'HB' } ] // [ { name: 'xiaoming' }, { region: 'HN' } ] } // Traverse the key for (let key of map.keys()) { console.log(key) // { name: 'zhangsan' } // { name: 'xiaoming' } } // Traverse value for (let key of map.values()) { console.log(key) // { region: 'HB' } // { region: 'HN' } } // Iterate over the Map using the forEach() method map.forEach(function(value, key) { console.log(key, value) // { name: 'zhangsan' } { region: 'HB' } // { name: 'xiaoming' } { region: 'HN' } }) 3. Determine key equality in Map About SameValue ( Object.is(NaN, NaN) // true Object.is(0, -0) // false The main difference between map.set(NaN, 0) map.set(0, 0) console.log(map.has(NaN)) // true console.log(map.has(-0)) // true 4. Copy or merge MapMaps can be copied like arrays let original = new Map([ [1, {}] ]) let clone = new Map(original) // Clone Map console.log(clone.get(1)); // {} console.log(original === clone) // false console.log(original.get(1) === clone.get(1)) // true Merge multiple maps let first = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]); let second = new Map([ [1, 'uno'], [2, 'dos'] ]); // When merging two Map objects, if there are duplicate key values, the latter will overwrite the former. // The spread operator essentially converts a Map object into an array. let merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three 5. Map Serialization Since the key of a Map can be of any data type, and JSON only allows strings as keys, it is generally not possible to convert a Map to JSON. However, you can try to serialize a Map in the following way: // Initialize Map(1) {"key1" => "val1"} const originMap = new Map([['key1', 'val1']]) //Serialize "[[\"key1\",\"val1\"]]" const mapStr = JSON.stringify(Array.from(originMap.entries())) // Deserialize Map(1) {"key1" => "val1"} const cloneMap = new Map(JSON.parse(mapStr)) 3. Performance Differences between Map and Object Memory usage The situation varies from browser to browser, but given a fixed amount of memory, Insert performance Map is slightly faster and is recommended if a large number Search speed The performance difference is minimal, but Deletion performance If the code involves a lot of deletion operations, it is recommended to choose This concludes the article on why we need Map when we already have You may also be interested in:
|
<<: Descending Index in MySQL 8.0
>>: In-depth understanding of the creation and implementation of servlets in tomcat
Beautiful code is the foundation of a beautiful we...
As we all know, binlog logs are very important fo...
Since the entire application needs to be deployed...
This article example shares the specific code of ...
What is bubbling? There are three stages in DOM e...
Detailed explanation and examples of database acc...
When we display long text, we often need to interc...
Table of contents 1. Install the proxy module 2. ...
1. Problem description The storage installed in t...
1. mysqlbinlog: [ERROR] unknown variable 'def...
List of HTML tags mark type Name or meaning effec...
First, I will give you the VMware 14 activation c...
1. Initialize data DROP TABLE IF EXISTS `test_01`...
The telnet in the Alpine image has been moved to ...
Table of contents Case Study Update account balan...