Table of Contents
1. map can accept keys of any type
1.1 Use objects as keys
2. map has no restrictions on key names
3. map is iterable
4. map的大小
5.结论
Home Web Front-end JS Tutorial A brief discussion on how to use map instead of pure JS objects

A brief discussion on how to use map instead of pure JS objects

Dec 02, 2020 pm 06:06 PM
javascript map

A brief discussion on how to use map instead of pure JS objects

JavaScript ordinary objects {key: 'value'} can be used to save structured data.

But one thing I find very annoying: the keys of the objects must be strings (or rarely used symbols).

What happens if numbers are used as keys? There is no error in this case:

const names = {
  1: 'One',
  2: 'Two',
};

Object.keys(names); // => ['1', '2']
Copy after login

JavaScript just implicitly converts the object's keys to strings. This is a tricky thing because you lose type consistency.

In this article, I will explain how the JavaScript Map object available in ES2015 solves many of the problems of ordinary objects, including converting keys to strings.

1. map can accept keys of any type

As mentioned above, if the object's key is not a string or symbol, JavaScript will implicitly convert it to a string.

Fortunately, map has no problem with key types:

const numbersMap = new Map();

numbersMap.set(1, 'one');
numbersMap.set(2, 'two');

[...numbersMap.keys()]; // => [1, 2]
Copy after login

1 and 2 are in numbersMap key. The type number of these keys remains unchanged.

You can use any key type in a map: numbers, booleans, and classic strings and symbols.

const booleansMap = new Map();

booleansMap.set(true, "Yep");
booleansMap.set(false, "Nope");

[...booleansMap.keys()]; // => [true, false]
Copy after login

booleansMap There is no problem with using boolean values ​​as keys.

Similarly, boolean keys don't work in normal objects.

Let's push the boundaries: can you use an entire object as a key in a map? sure!

1.1 Use objects as keys

Suppose you need to store some data related to the object, but do not attach the data to the object itself.

You cannot do this with ordinary objects.

One solution is to use a set of tuples of object values:

const foo = { name: 'foo' };
const bar = { name: 'bar' };

const kindOfMap = [
  [foo, 'Foo related data'],
  [bar, 'Bar related data'],
];
Copy after login

kindOfMap is an array containing a pair of objects and the associated value.

The biggest problem with this approach is that the time complexity of accessing the value by key is O(n). You have to loop through the entire array to get the desired value by key:

function getByKey(kindOfMap, key) {
  for (const [k, v] of kindOfMap) {
    if (key === k) {
      return v;
    }
  }
  return undefined;
}

getByKey(kindOfMap, foo); // => 'Foo related data'
Copy after login

With WeakMap (a specialized version of Map) you don't need to bother with this. It accepts objects as keys. The main difference between

Map and WeakMap is that the latter allows objects that are keys to be garbage collected, thus preventing memory leaks.

The cost of refactoring the above code to use WeakMap is trivial:

const foo = { name: 'foo' };
const bar = { name: 'bar' };

const mapOfObjects = new WeakMap();

mapOfObjects.set(foo, 'Foo related data');
mapOfObjects.set(bar, 'Bar related data');

mapOfObjects.get(foo); // => 'Foo related data'
Copy after login

as opposed to Map, WeakMap Only accepts objects as keys and has a reduced method set.

2. map has no restrictions on key names

Any object in JavaScript inherits properties from its prototype object. The same goes for regular JavaScript objects.

If you override properties inherited from the prototype, you may break code that depends on these prototype properties:

function isPlainObject(value) {
  return value.toString() === '[object Object]';
}

const actor = {
  name: 'Harrison Ford',
  toString: 'Actor: Harrison Ford'
};

// Does not work!
isPlainObject(actor); // TypeError: value.toString is not a function
Copy after login

Properties defined on the object actortoString Overrides the toString() method inherited from the prototype. Because it relies on the toString() method, this breaks isObject().

Check the list of properties and methods that ordinary objects inherit from the prototype. Avoid using these names to define custom properties.

For example, suppose you have a user interface that manages some custom fields. Users can add fields by specifying names and values:

A brief discussion on how to use map instead of pure JS objects

It would be convenient to store the state of custom fields into a normal object:

const userCustomFields = {
  'color':    'blue',
  'size':     'medium',
  'toString': 'A blue box'
};
Copy after login

But The user may choose a custom field name such as toString (as shown in the example), constructor, etc., which may break your object.

Don't create keys on ordinary objects by accepting user input!

map does not have this problem. The name of the key is not restricted:

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
Copy after login

The method toString() will work regardless of whether the actorMap has a property named toString .

3. map is iterable

In order to traverse the properties of ordinary objects, you must use other auxiliary static functions, such as Object.keys() or Object.entries() (available in ES2017):

const colorsHex = {
  'white': '#FFFFFF',
  'black': '#000000'
};

for (const [color, hex] of Object.entries(colorsHex)) {
  console.log(color, hex);
}
// 'white' '#FFFFFF'
// 'black' '#000000'
Copy after login

Object.entries(colorsHex) Returns an array of key-value pairs extracted from the object.

However, the map itself is iterable:

const colorsHexMap = new Map();

colorsHexMap.set('white', '#FFFFFF');
colorsHexMap.set('black', '#000000');

for (const [color, hex] of colorsHexMap) {
  console.log(color, hex);
}
// 'white' '#FFFFFF'
// 'black' '#000000'
Copy after login

colorsHexMap is iterable. You can use it anywhere iterable: for() loops, unroll operators [...map], etc.

map also provides other methods that return iterations: map.keys() iterates over keys, map.values() iterates over values.

4. map的大小

普通对象的另一个问题是你无法轻松确定其拥有的属性数量:

const exams = {
  'John Smith': '10 points',
  'Jane Doe': '8 points',
};

Object.keys(exams).length; // => 2
Copy after login

要确定 exams 的大小,你必须通过它所有键来确定它们的数量。

map 提供了一种替代方法,通过它的访问器属性 size 计算键值对:

const examsMap = new Map([
  ['John Smith', '10 points'],
  ['Jane Doe', '8 points'],
]);
  
examsMap.size; // => 2
Copy after login

确定 map 的大小更加简单:examsMap.size

5.结论

普通的 JavaScript 对象通常可以很好地保存结构化数据。但是它们有一些限制:

  1. 只能用字符串或符号用作键
  2. 自己的对象属性可能会与从原型继承的属性键冲突(例如,toStringconstructor 等)。
  3. 对象不能用作键

所有这些问题都可以通过 map 轻松解决。而且它们提供了诸如迭代器和易于进行大小查找之类的好处。

不要将 map 视为普通对象的替代品,而应视为补充。

你知道 map 相对于普通对象的其他好处吗?请在下面写下你的评论!

原文地址:https://dmitripavlutin.com/maps-vs-plain-objects-javascript/

译文地址:https://segmentfault.com/a/1190000020660481

更多编程相关知识,请访问:编程课程!!

The above is the detailed content of A brief discussion on how to use map instead of pure JS objects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles