Table of Contents
es6 map
1-2-1 Add mapping element" >1-2-1 Add mapping element
##1-2-2 Mapping set length Use the " >##1-2-2 Mapping set length Use the
1-2-3 Get elementsGet the element through the get() method and pass in the key of the target" >1-2-3 Get elementsGet the element through the get() method and pass in the key of the target
Home Web Front-end Front-end Q&A Is es6 map a reference type?

Is es6 map a reference type?

Jan 11, 2023 pm 04:59 PM
es6 map

Map is a reference type; map (collection) is a new reference data type in es6, which represents the mapping relationship of data. Data in the map collection data type is stored in a "key/value" manner. You can use the properties of the object as the key and use the properties to reference the value; the map can be created using new, for example "const myMap = new Map();" .

Is es6 map a reference type?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

map is a reference type.

es6 map

Before ES6, to implement 'key'=>'value' in JavaScript, which is what we often call key-value pairs, is to use Object to complete. However, this implementation method has problems in special scenarios. ES6 has introduced a new collection type called Map, which brings a true key-value pair storage mechanism to the language.

map (collection) is a new reference data type in es6, which represents the mapping relationship of data; data in the map collection data type is stored in a "key/value" manner, and you can use the properties of the object As keys, use properties to reference values.

1-1 Create Map

Use the new keyword to instantiate a map

let m = new Map();

console.log(m);
// Map(0) {}
Copy after login

Initialization when creating:
Pass in a two-dimensional array parameter (an iterable object, the key value is passed in as an array internally)
For each sub-array, the first element corresponds to map key, the second element is the value

let m = new Map([[{}, 222], [{}, '123']]);

console.log(m);
// Map(2) { {} => 222, {} => '123' }
Copy after login

##1-2 Map Api

1-2-1 Add mapping element

Add through the set() method, passing in two parameters, the first The key of the map is passed in first, and the value of the map is passed in the second one. What is returned is the mapping set (meaning it can be added in a chain)

let m = new Map();

m.set('prop', '值');

console.log(m);
// Map(1) { 'prop' => '值' }
Copy after login

Chained addition of key values

let m = new Map();

m.set('prop', '值').set('prop2', false).set('num', {id: 13});

console.log(m);
// Map(3) { 'prop' => '值', 'prop2' => false, 'num' => { id: 13 } }
Copy after login

##1-2-2 Mapping set length Use the

size

attribute to get the number of elements in the current collection<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>let m = new Map(); m.set(&amp;#39;prop&amp;#39;, &amp;#39;值&amp;#39;).set(&amp;#39;prop2&amp;#39;, false).set(&amp;#39;num&amp;#39;, {id: 13}); console.log(m.size);</pre><div class="contentsignin">Copy after login</div></div>

1-2-3 Get elementsGet the element through the get() method and pass in the key of the target

let m = new Map();

m.set(&#39;prop&#39;, &#39;值&#39;).set(&#39;prop2&#39;, false).set(&#39;num&#39;, {id: 13});

console.log(m.get(&#39;prop2&#39;));
// false
Copy after login

##1-2-4 Delete the elementDelete an element in the mapping collection through the delete() method and return a Boolean value indicating whether the deletion is successful or failed
let m = new Map();

m.set(&#39;prop&#39;, &#39;值&#39;).set(&#39;prop2&#39;, false).set(&#39;num&#39;, {id: 13});

m.delete(&#39;prop2&#39;);
// true

console.log(m.get(&#39;prop2&#39;), m.size);
// undefined 2
Copy after login

1-2-5 Detect whether the element is ExistenceUse the has() method to detect whether the target element exists and return the Boolean value of the detection result
let m = new Map();

m.set(&#39;prop&#39;, &#39;值&#39;).set(&#39;prop2&#39;, false).set(&#39;num&#39;, {id: 13});

m.delete(&#39;prop2&#39;);
// true

console.log(m.has(&#39;prop2&#39;), m.has(&#39;num&#39;));
// false  true
Copy after login

1-2-6 Clear the element MethodUse the clear() method to clear all elements and return a Boolean value of successful clearing
let m = new Map();

m.set(&#39;prop&#39;, &#39;值&#39;).set(&#39;prop2&#39;, false).set(&#39;num&#39;, {id: 13});

m.clear();
// true

console.log(m);
// Map(0) {}
Copy after login

##1-3 Sequence With iterationmap can iterate elements according to the order of insertion The mapping instance will provide (iterator). It can generate an array in the form of [key, value] in the order of insertion, and can pass entries () method (or provided Symbol.iterator) iterator interface traversal.

let m = new Map();

m.set(&#39;prop&#39;, &#39;值&#39;).set(&#39;prop2&#39;, false).set(&#39;num&#39;, {id: 13});

console.log(m.entries === m[Symbol.iterator]);// true

for(let k1 of m.entries()){
    console.log(k1);
    // [ &#39;prop&#39;, &#39;值&#39; ]
    // [ &#39;prop2&#39;, false ]
    // [ &#39;num&#39;, { id: 13 } ]
    // 遍历的属性即对应映射元素的键值对数组
}

for(let k2 of m.keys()){
    console.log(k2);
    // prop
    // prop2
    // num
    // 遍历的属性对应映射元素的键
}

for(let k3 of m.values()){
    console.log(k3);
    // 值
    // false
    // { id: 13 }
    // 遍历的属性对应映射元素的值
}

for(let k4 of m[Symbol.iterator]()){
    console.log(k4);
    // [ &#39;prop&#39;, &#39;值&#39; ]
    // [ &#39;prop2&#39;, false ]
    // [ &#39;num&#39;, { id: 13 } ]
    // 遍历的属性即对应映射元素的键值对数组
}
Copy after login


1-4 Comparison with ObjectMemory usage

Browser The difference will lead to different memory usage between the two storage methods. However, given the memory size, map stores about 50% more key-value pairs than Object.
  • Insert Performance

    Insertion speed The performance of map and Object above are roughly the same, but if the code involves a large number of insertions, it is recommended to use map
  • Find speed

    The difference is smaller Small, Object is better when it contains only a small number of key-value pairs
  • Delete performance

    Object's delete() performance is poor, while map's delete() The performance is good. If the data involves a large number of deletion operations, it is recommended to use map
  • [Related recommendations:
    javascript video tutorial
  • ,
programming video

The above is the detailed content of Is es6 map a reference type?. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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 does springboot read lists, arrays, map collections and objects in yml files? How does springboot read lists, arrays, map collections and objects in yml files? May 11, 2023 am 10:46 AM

application.yml defines the list collection. The first way is to use the @ConfigurationProperties annotation to obtain all the values ​​​​of the list collection type:code:status:-200-300-400-500. Write the entity class corresponding to the configuration file. What needs to be noted here is that defining the list Collection, first define a configuration class Bean, and then use the annotation @ConfigurationProperties annotation to obtain the list collection value. Here we will explain the role of the relevant annotations. @Component hands over the entity class to Spring management @ConfigurationPropertie

How to set expiration time map in Java How to set expiration time map in Java May 04, 2023 am 10:13 AM

1. Technical background In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system. But in many cases, if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to increase the complexity of the system in order to use caching. So does Java itself have any useful lightweight caching components? The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging. 2. Technical effects to realize common functions of cache, such as outdated deletion strategy, hotspot data warm-up 3. ExpiringMap3.

Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

What are the ways to implement thread safety for Map in Java? What are the ways to implement thread safety for Map in Java? Apr 19, 2023 pm 07:52 PM

Method 1. Use HashtableMapashtable=newHashtable(); This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe publicsynchronizedbooleancontainsKey(Objectkey){Entrytab[]=table;inthash=key.hashCode( );intindex=(hash&0x7FFFFFFF)%tab.leng

How to convert objects to Maps in Java - using BeanMap How to convert objects to Maps in Java - using BeanMap May 08, 2023 pm 03:49 PM

There are many ways to convert javabeans and maps, such as: 1. Convert beans to json through ObjectMapper, and then convert json to map. However, this method is complicated and inefficient. After testing, 10,000 beans were converted in a loop. , it takes 12 seconds! ! ! Not recommended. 2. Obtain the attributes and values ​​of the bean class through Java reflection, and then convert them into the key-value pairs corresponding to the map. This method is the second best, but it is a little more troublesome. 3. Through net.sf.cglib.beans.BeanMap Method in the class, this method is extremely efficient. The difference between it and the second method is that because of the use of cache, the bean needs to be initialized when it is first created.

How to configure and use the map module in Nginx server How to configure and use the map module in Nginx server May 21, 2023 pm 05:14 PM

The map directive uses the ngx_http_map_module module. By default, nginx loads this module unless artificially --without-http_map_module. The ngx_http_map_module module can create variables whose values ​​are associated with the values ​​of other variables. Allows classification or simultaneous mapping of multiple values ​​​​to multiple different values ​​​​and storage in a variable. The map directive is used to create a variable, but only performs the view mapping operation when the variable is accepted. For processing requests that do not reference variables, this The module has no performance shortcomings. 1.ngx_http_map_module module instruction description map syntax

What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

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

See all articles