Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

When is it appropriate to use Map

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "when is appropriate to use Map". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

"Map" mapping is a classical type of data structure, in which data exists in the form of key-value pairs of "key/value".

The default value of MapObject does not contain any value by default, but only contains explicitly inserted keys. An Object has a prototype, and the key name on the prototype may conflict with the key name conflict type set on your object. Any number of String or Symbol length key-value pairs can be obtained by size attribute. The number of key-value pairs can only be calculated manually. The performance is better in scenarios where frequent key-value pairs are added and deleted.

Basic usage of Map

Const testMap = new Map () let str = 'not learning today', num = 666, keyFunction = function () {}, keySymbol = Symbol ('Web'), keyNull = null, keyUndefined = undefined, keyNaN = NaN / / add key-value pairs testMap.set (' key', 'value') / / Map (1) {"key" = > "value"} testMap.set (str) TestMap.set (num, 'front-end Sneaker') testMap.set (keyFunction,' your function is great') testMap.set (keySymbol, 'big front-end') testMap.set (keyNull,'I'm a Null') testMap.set (keyUndefined,'I'm a Undifined') testMap.set (keyNaN) 'I am a NaN') testMap.get (function () {}) / / undefined testMap.get (Symbol (' Web')) / / undefined / / although NaN! = = NaN but there is no difference as a Map key name testMap.get (NaN) / / "I am a NaN" testMap.get (Number ('NaN')) / / "I am a NaN"

Except for NaN, other get methods of "Map" are obtained by comparing whether the key names are equal (= =). If not, undefined is returned.

Compare Map and Object

Define

/ / Map const map = new Map (); map.set ('key',' value'); / / Map (1) {"key" = > "value"} map.get ('key'); / /' value' / / Object const someObject = {}; someObject.key = 'value'; someObject.key; / /' value'

It is obvious here that the behavior of the definition is very similar, and you must not see when the use of "Map" is the best practice, so don't rush to move on.

Key name type

JavaScript "Object" only accepts two types of key names: String and Symbol. You can use other types of key names, but eventually JavaScript is implicitly converted to a string.

Const obj = {} / / look directly at several special key names obj [true] = 'Boolean' obj [1] =' Number' obj [{'front end': 'Sneaker'}] =' 666' Object.keys (obj) / / ["1", "true", "[object Object]"]

Let's take a look at "Map", which receives any type of key name and retains its key name type (for a simple example here, see the basic use of "Map" at the beginning of the article)

Const map = new Map (); map.set (1, 'value'); map.set (true,' value'); map.set ({'key':' value'}, 'value'); for (const key of map.keys ()) {console.log (key) } / / 1 / / true / / {key: "value"} / / in addition, Map also supports regular as key name map.set (/ ^ 1 [3456789]\ d {9} $/, 'Mobile number regular') / / Map (1) {/ ^ 1 [3456789]\ d {9} $/ = > "Mobile phone number regular"}

"Map" supports regular expressions as key names, which is not allowed to report errors directly in Object

Prototype Prototype

"Object" is different from "Map", it is not just what you see on the surface. "Map" contains only the key-value pairs you define, but the "Object" object has some built-in properties in its prototype.

Const newObject = {}; newObject.constructor; / / native code Object () {[native code]}

If you do not traverse the object properties correctly, it may cause problems, resulting in unexpected bug.

Const countWords = (words) = > {const counts = {}; for (const word of words) {counts [word] = (counts [word] | | 0) + 1;} return counts;}; const counts = countWords (['constructor',' creates', 'asides,' bug']); / / {constructor: "function Object () {[native code]} 1", creates: 1, a: 1, bug: 1}

This example is inspired by Effective TypeScript [1].

Iterator

"Map" is iterable and can be iterated directly, such as forEach loop or for...of... Cycle

/ / forEach const map = new Map (); map.set ('key1',' value1'); map.set ('key2',' value2'); map.set ('key3',' value3'); map.forEach ((value, key) = > {console.log (key, value);}); / / key1 value1 / / key2 value2 / / key3 value3 / / for...of... For (const entry of map) {console.log (entry);} / ["key1", "value1"] / / ["key2", "value2"] / / ["key3", "value3"]

But it cannot be iterated directly for "Object". When you try to iterate, it will result in an error.

Const object = {key1: 'value1', key2:' value2', key3: 'value3',}; for (const entry of object) {console.log (entry);} / / Uncaught TypeError: object is not iterable

At this point, you need an extra step to retrieve its key name, key value, or key value pair.

For (const key of Object.keys (object)) {console.log (key);} / key1 / / key2 / / key3 for (const value of Object.values (object)) {console.log (value);} / / value1 / / value2 / / value3 for (const entry of Object.entries (object)) {console.log (entry) } / / ["key1", "value1"] / / ["key2", "value2"] / / ["key3", "value3"] for (const [key,value] of Object.entries (object)) {console.log (key,value);} / "key1", "value1" / / "key2", "value2" / / "key3", "value3"

Of course, you can also use for...in... Iterate through the key name

For (const key in object) {console.log (key);} / / key1 / / key2 / / key3

Element order and length

Map keeps tracking the length so that it can be accessed in O (1) complexity

Const map = new Map (); map.set ('key1',' value1'); map.set ('key2',' value2'); map.set ('key3',' value3'); map.size; / / 3

On the other hand, for "Object", if you want to get the attribute length of an object, you need to manually iterate it to O (n) complexity and the attribute length is n.

In the example mentioned above, we can see that "Map" always returns the key name in the order in which it is inserted. But "Object" is not. Starting with ES6, String and symbol keys are saved sequentially, but keys saved to String by implicit conversion are out of order.

Const object = {}; object ['key1'] =' value1'; object ['key0'] =' value0'; object; / / {key1: "value1", key0: "value0"} object [20] = 'value20'; object; / / {20: "value20", key1: "value1", key0: "value0"} Object.keys (object) .length; / / 3

What is the best practice of Object/Map

The above is the basic difference between "Map" and "Object", which needs to be considered when solving the problem.

When the insertion order is something you need to consider when solving the problem, and you currently need to use keys other than String and Symbol, then "Map" is the best solution.

If you need to traverse key-value pairs (and you need to consider the order), then I think "Map" needs to be given priority.

Map is a pure hash structure, while Object is not (it has its own internal logic). Map performs better and performs better in scenarios where key-value pairs are frequently added and deleted. So when you need to manipulate data frequently, you can also give priority to Map.

To take another practical example, for example, there is a user operation function of a custom field, and the user can customize the field through the form, then it is best to use Map at this time, because it is likely to destroy the original object.

Const userCustomFields = {'color':' blue', 'size':' medium', 'toString':' A blue box'}

At this point, the user-defined toString will destroy the original object, and the "Map" key name accepts any type, which has no effect.

Function isMap (value) {return value.toString () = ='[object Map]';} const actorMap = new Map (); actorMap.set ('name',' Harrison Ford'); actorMap.set ('toString',' Actor: Harrison Ford'); / / Works! IsMap (actorMap); / / = > true

When you need to deal with some attributes, then "Object" is completely useful, especially when you need to deal with JSON data. Because "Map" can be of any type, there is no native method that can convert it to JSON.

Var map = new Map () map.set ('key','value') JSON.stringify (map) / / "{}"

When you need regular expression judgment to deal with some business logic, "Map" will be your best solution.

Const actions = () = > {const functionA = () = > {/ * do sth*/} const functionB = () = > {/ * do sth*/} const functionC = () = > {/ * send log*/} returnnewMap ([[/ ^ guest_ [1-4] $/, functionA], [/ ^ guest_5 $/, functionB], [/ ^ guest_.*$/,functionC], / /...])} const onButtonClick = (identity) Status) = > {let action = [... actions ()] .filter (([key,value])) = > (key.test (`${identity} _ ${status}`)) action.forEach (([key,value])) = > value.call (this))}

Using the characteristics of the array loop, the logic that meets the regular conditions will be executed, so you can execute both common logic and separate logic, because of the existence of regularities, you can open your imagination and unlock more games, and more related Map usage examples can see the more elegant writing of JavaScript complex judgments.

This is the end of the content of "when is appropriate to use Map". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report