How does JS understand the new data structures of Set and Map in ES6?

Table of contents

I. Introduction

2. Set

1.Set data structure definition

2. Characteristics of the Set data structure

3. Basic use of Set data structure

4.Set traversal data

5. Set usage scenarios

6. The use of WeakSet

7. Garbage collection mechanism

3. Map

1. Map data structure definition

2. Characteristics of Map data structure

3. Basic use of Map data structure

 4. Map traversal data

5. Map usage scenarios

6. Use of WeakMap

7. Garbage collection


I. Introduction

Set is a data structure called a collection , and Map is a data structure called a dictionary

What is a collection? What is a dictionary again?

A collection is a combination of unordered, associated, and non-repeating memory structures [called elements in mathematics]

A dictionary is a collection of elements. Each element has a field called key, and the keys of different elements are different

the difference?

Common point : Both sets and dictionaries can store unique values.
Difference : Sets store elements in the form of [value, value], and dictionaries store elements in the form of [key, value].

The following two data structures are explained in detail

2. Set

1.Set data structure definition

Used to store unique values ​​of any type, whether primitive or object reference.

2. Characteristics of the Set data structure

(1) Only values ​​can be saved without key names
(2) Strict type detection such as string numbers are not equal to numeric numbers
(3) Values ​​are unique
(4) The traversal order is the order of addition, which is convenient for saving callback functions

3. Basic use of Set data structure

(1) add: add element

Use add to add elements, it is not allowed to add the same value repeatedly

let set = new Set()
set.add(1).add(1).add(1);
console.log(set.values());  // [1]

Set strictly distinguishes value types 1 and '1' as belonging to two different values

let set = new Set();
set.add(1);
set.add('1');
console.log(set.values());  // [1,'1']

(2) has: Detects whether the element exists, returns a Boolean value, and returns true if it exists

let set = new Set();
set.add(1);
set.has(1); // true

(3) size returns the length of the Set

let set = new Set(['zs', 'lisi']);
console.log(set.size); // 2

(4) delete: Delete a single element method, the return value is boolean type

let set = new Set(['zs', 'lisi']);
set.delete('zs');
console.log(set.values()); // ['lisi']

(5) clear: clear all members, no return value

let set = new Set(['zs', 'lisi']);
set.clear();
console.log(set.values()); // []

(6) Array conversion

You can use the dot syntax or the Array.form static method to convert the Set type into an array, so that you can use the array processing function

let set = new Set(['zs', 'lisi']);
console.log([...set]); //  ['zs', 'lisi']
console.log(Array.from(set)); //  ['zs', 'lisi']

4.Set traversal data

(1). forEach(): Use the callback function to traverse each member

let set = new Set(['zs', 'lisi'])
set.forEach((item, index) => {
    console.log(item, index); // zs zs  lisi lisi
});

(2). keys(): returns the traverser of the key name

let set = new Set(['zs', 'lisi']);
for (let i of set.keys()) {
    console.log(i); // zs lisi
}

(3). values(): returns the traverser of the key value

let set = new Set(['zs', 'lisi']);
for (let i of set.values()) {
    console.log(i); // zs lisi
}

(4) entries(): returns a traverser of key-value pairs

let set = new Set(['zs', 'lisi']);
for (let i of set.entries()) {
    console.log(i); // ['zs','zs'] ['lisi','lisi']
}

5. Set usage scenarios

(1). Use Set to achieve deduplication

Implement string deduplication

let str = 'helloworld';
console.log([...new Set(str)]); // ['h', 'e', 'l', 'o', 'w', 'r', 'd']

Implement array deduplication

let arr = [1, 2, 3, 4, 1, 2];
console.log([...new Set(arr)]); // [1, 2, 3, 4]

(2). Realize union, intersection and difference

            let a = new Set([1, 2, 3]);
            let b = new Set([2, 3, 4]);

            // 并集
            let bingji = new Set([...a, ...b]);
            console.log(bingji.values()); // [1,2,3,4]
            // 交集
            let jiaoji = new Set([...a].filter((x) => b.has(x)));
            console.log(jiaoji.values()); // [2,3]
            // (a 相对于 b 的)差集
            let chaji = new Set([...a].filter((x) => !b.has(x)));
            console.log(chaji.values()); // [1]

6. The use of WeakSet

The WeakSet structure also does not store duplicate values, and its members must only be values ​​of object type

Features of WeakSets  

   (1). Garbage collection does not consider WeakSet, that is, the reference counter is not incremented by one when it is referenced by WeakSet, so when the object is not referenced, it will be deleted regardless of whether the WeakSet is in use or not. (2). Because WeakSet is a weak reference, due to other operations on
   members It may not exist, so operations such as forEach ( ) traversal (3) cannot be performed.
   Also because of weak references, the WeakSet structure does not have methods such as keys ( ), values ​​( ), entries ( ) and size attributes
   (4). Because it is weak Reference So use WeakSet when you want to automatically delete data when the external reference is deleted

   (5). WeakSet has no size attribute

(1) The value of WeakSet must be an object type, if it is another type, an error will be reported

            // 正确声明
            let weakSet = new WeakSet([
                [1, 2],
                [3, 4],
            ]);
            // 错误声明
            let weakSet1 = new WeakSet([1, 2]); //  Invalid value used in weak set

(2) When using WeakSet to save DOM nodes, when the DOM node is deleted, WeakSet will automatically delete the reference to the DOM node, so there is no need to worry about the memory leak caused by the removal of the dom node from the document

7. Garbage collection mechanism

The objects saved by WeaSet will not increase the reference counter , and if an object is no longer referenced, it will be automatically deleted.

        let set = new WeakSet();
        let arr = ['zs', 'lisi'];
        set.add(arr, 123);
        arr = null;
        console.log(set);
        setTimeout(() => {
            console.log(set);
        }, 1000);

3. Map

1. Map data structure definition

Map is a structure of a set of key-value pairs, which is used to solve the problem that objects cannot be used as keys in the past

2. Characteristics of Map data structure

(1) It has extremely fast search speed
(2) Functions, objects, and basic types can all be used as keys or values

3. Basic use of Map data structure

(1) Set adds elements and supports chain operations

            let map = new Map([]);
            map.set('name', 'zs');
            map.set('age', '18');
            map.set('hobby', [1, 2, 3]).set('a', 'b');
            console.log(map);

(2).get get element

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            console.log(map.get('name')); // 'zs'

(3).size Get the quantity and return the map length

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            console.log(map.size); // 2

(4).has uses the key value to detect whether it exists, returns a Boolean value, and returns true if it exists

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            console.log(map.has('name')); // true
            console.log(map.has('hobby')); // false

(5).delete method to delete a single element

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            map.delete('name');
            console.log(map.has('name')); // false

(6). The clear method clears all elements of the map

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            map.clear('name');
            console.log(map.size); // 0

(7). Data conversion

You can use the expansion syntax or the Array.form static method to convert the Map type into an array, so that you can use the array processing function 

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            console.log([...map]);
            console.log(Array.from(map));

 4. Map traversal data

keys(): the traverser that returns the key name
values(): the traverser that returns the key value
entries(): the traverser that returns all members
forEach(): traverses all members of the Map

            let map = new Map([
                ['name', 'zs'],
                ['age', 18],
            ]);
            map.forEach((value, key) => {
                console.log(key, value); // name zs  // age 18
            });

            for (let i of map.keys()) {
                console.log(i); // name age
            }

            for (let value of map.values()) {
                console.log(value); // zs 18
            }

            for (let entries of map.entries()) {
                console.log(entries); // ['name','zs'] ['age',18]
            }
            // 等同于上面的 map.entries()
            for (let [key, value] of map.entries()) {
                console.log(key, value); // name zs // age 18
            }

5. Map usage scenarios

(1) When there are multiple form elements on the page that need data interaction, Map can be used to store form data

            const formData = new Map();
            formData.set('username', 'zs');
            formData.set('password', '123456');
            const username = formData.get('username'); //zs
            const password = formData.get('password'); //123456

By using Map to manage data, the code can be more concise and easy to maintain

6. Use of WeakMap

A WeakMap object is a collection of key/value pairs

(1) The key name must be an object
(2) WeaMap has a weak reference to the key name, and the key value is a normal reference
(3) Garbage collection does not consider the WeaMap key name, it will not change the reference counter, and the key is not referenced elsewhere Delete immediately
(4) Because WeakMap is a weak reference, because other operating members may not exist, it is not possible to perform operations such as forEach ( ) traversal (
5) also because of weak references, the WeaMap structure does not have keys ( ), values ​​( ) , entries() and other methods and size attribute
(6) When the external reference of the key is deleted, use WeakMap when you want to automatically delete the data

(1) The value of WeakMap must be an object type, if it is another type, an error will be reported

            let weakMap = new WeakMap();
            // 正确声明
            weakMap.set({ name: 'zs' }, 'lisi');
            // 错误声明
            weakMap.set(1, 2); // Invalid value used as weak map key
            // at WeakMap.set (<anonymous>)
            weakMap.set(null, 1); //  Invalid value used as weak map key
            // at WeakMap.set (<anonymous>)

(2) Use WeakMap to save DOM nodes

    <body>
        <div>zs</div>
        <div>lisi</div>
    </body>
    <script>
        const map = new WeakMap();
        document.querySelectorAll('div').forEach((item) => map.set(item, item.innerHTML));
        console.log(map); //WeakMap {div => "zs", div => "lisi"}
    </script>

7. Garbage collection

The key name object of WakeMap will not increase the reference counter, if an object is not referenced, it will be automatically deleted.

In the following example, the memory is cleared when obj is deleted, because WeakMap is a weak reference and does not generate reference counts

        let map = new WeakMap();
        let obj = { name: 'zs' };
        map.set(obj, 'zs');
        obj = null;

        console.log(map);

        setTimeout(() => {
            console.log(map);
        }, 1000);

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131132594