Talking about the mapping and collection of JS

Table of contents

introduction

Map

features

properties and methods

create

Add

Obtain

Is there a value

delete

empty

get length

iterator of keys

iterator of values

iterator of key-value pairs

traverse

scenes to be used

Describe the mapping relationship

cache

Set

features

properties and methods

Create and initialize

Add

delete

other properties

scenes to be used

Array deduplication

set operation

WeakMap

features

properties and methods

Create and initialize

other properties

scenes to be used

property privatization

avoid memory leaks

WeakSet

features

properties and methods

Create and initialize

other properties

scenes to be used

avoid memory leaks

Summarize


introduction

Map (mapping) and Set (collection) are data structures introduced by ES6, which provide a more flexible and efficient way to store and access data. This article will introduce the concept and use of these two data structures and two new data structures, WeakMap (weak mapping) and WeakSet (weak collection).

Map

Map is a collection that stores data in the form of key-value pairs. Its structure is similar to an object, and it is also a collection of key-value pairs, but the key of a Map can be any type of value, including objects, functions, and primitive types. It can be said that Map is an extension of objects.

features

  1. The key is unique, and the key-value pairs added later will replace the previous ones
  2. The key-value is ordered, using the Map object will get each key-value pair in the order of insertion
  3. All types of values ​​can be used as keys

properties and methods

create

We can create an empty Map by the following code

const map = new Map()
console.log(map); // Map(0) {}

Assign initial value: map uses [] to represent the hierarchical structure, the first dimension is the number of mappings, the second dimension is the specific value, and the structure is [key, value]

const map = new Map<string, string | number>([['name', '阿黄'], ['age', 20]])
console.log(map); // Map(2) { 'name' => '阿黄', 'age' => 20 }

Add

Add a key-value pair by set(key, value), if the key already exists, the corresponding value will be updated

const map = new Map()
map.set('name', '阿黄')
console.log(map);// Map(1) { 'name' => '阿黄' }
map.set('name', '小黑')
console.log(map);// Map(1) { 'name' => '小黑' }

Obtain

Use get(key) to return the value corresponding to the key, or undefined if the value does not exist

const map = new Map()
console.log(map.get('name')); // undefined
map.set('name', '阿黄')
console.log(map.get('name')); // 阿黄

Is there a value

Use map.has(key) to determine whether there is a value corresponding to the key

const map = new Map()
console.log(map.has('name')); // false
map.set('name', '阿黄')
console.log(map.has('name')); // true

delete

Delete the value of map by delete(key)

const map = new Map()
map.set('name', '阿黄')
console.log(map); // Map(1) { 'name' => '阿黄' }
map.delete('name')
console.log(map); // Map(0) {}

empty

Use the map.clear() function to clear the map

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
console.log(map); // Map(2) { 'name' => '阿黄', 'age' => 12 }
map.clear()
console.log(map); // Map(0) {}

get length

map can get the number of subsets by size

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
console.log(map.size); // 2

iterator of keys

Use the keys function to return an iterator over all the keys in the Map

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
console.log(map.keys()); // { 'name', 'age' }

iterator of values

Similar to keys, the values ​​function can return an iterator of all the values ​​in the Map

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
console.log(map.values()); //  { '阿黄', 12 }

iterator of key-value pairs

Use entries or the Symbol.iterator function to return the key-value pairs of the Map

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
console.log(map.entries()); // { [ 'name', '阿黄' ], [ 'age', 12 ] }
console.log(map[Symbol.iterator]()); // { [ 'name', '阿黄' ], [ 'age', 12 ] }

traverse

Use the forEach function to traverse, similar to the forEach of the array (the second item of the array is the index), the callback function returns three values, namely value, key, map

const map = new Map()
map.set('name', '阿黄')
map.set('age', 12)
map.forEach((val, key, map) => {
    console.log(val, key, map);
})
// 阿黄 name Map(2) { 'name' => '阿黄', 'age' => 12 }
// 12 age Map(2) { 'name' => '阿黄', 'age' => 12 }

scenes to be used

Describe the mapping relationship

In the object, we can only use string or symbol to describe the value of the key, and Map can describe the relational mapping very well

const map = new Map()
map.set(['meat', 'fish'], '都是阿黄爱吃的')
console.log(map); // Map(1) { [ 'meat', 'fish' ] => '都是阿黄爱吃的' }

cache

We use the uniqueness of Map's index to apply it to cache operations. In the following code, we use a function as the key of the map. The first call to the function will trigger the set operation, and subsequent operations will directly use get to obtain the corresponding value.

const cache = new Map();
const temp = (key: any) => cache.get(key) ?? (cache.set(key, getNum(1, 2)), cache.get(key))// 缓存操作,首次访问会执行set操作
const getNum = (a: number, b: number) => a + b
console.log(temp(getNum))
console.log(temp(getNum))

Set

Set is an unordered and unique collection (which can be regarded as a mathematical collection), which can store any type of value, including objects, functions, and primitive types. Its structure is similar to an array, but the values ​​in it are not allowed to be repeated, which is similar to the key value of Map.

features

  1. Member values ​​are unique
  2. Unorderedness of values ​​(data storage does not rely on indexes, but hash tables)

properties and methods

Create and initialize

const set = new Set<string>()
console.log(set);// Set(0) {}

Initialization can use [value] or any array for assignment

const set = new Set<string>(['阿黄'])
console.log(set);// Set(1) { '阿黄' }

Add

The new sub-item of Set is not the same as that of Map, you can use the add function to operate

const set = new Set(['阿黄'])
set.add('小黑')
console.log(set);// Set(2) { '阿黄', '小黑' }

delete

set uses delete to delete a single item of the collection

const set = new Set<string>(['阿黄'])
set.delete('阿黄')
console.log(set);// Set(0) {}

other properties

The rest of the properties are almost the same as those of Map, so we won’t go into details on usage. In addition, the iterator method of Set is special. The results of using set.values() and set.keys() are the same, because the key and value of Set are both value values.

const set = new Set<string>(['阿黄'])
console.log(set.values()); // [Set Iterator] { '阿黄' }
console.log(set.keys()); // [Set Iterator] { '阿黄' }
console.log(set.entries()); // [Set Entries] { ['阿黄', '阿黄'] }

scenes to be used

Array deduplication

const set = new Set([6, 6, 4, 2, 3, 4, 3, 3, 1, 5, 5, 2]);
console.log(set);// Set(6) { 6, 4, 2, 3, 1, 5 }

set operation

intersection, union, difference

const set = new Set([1, 2, 3, 4, 5]);
const set2 = new Set([1, 3, 5, 7, 9]);
// 交集
console.log([...set].filter(it => set2.has(it)));
// 并集
console.log(new Set([...set, ...set2]));
// 差集
console.log([...set].filter(it => !set2.has(it)));

WeakMap

Before understanding WeakMap, first look at the code

let obj: any = {
    name: "阿黄"
}
const map = new Map([[obj, "阿黄"]]);
obj = null
console.log(map);// Map(1) { { name: '阿黄' } => '阿黄' }

In the above code, we create a new object type variable and assign it as a key to the Map. When we delete obj, the key value in the Map does not change, indicating that the two are in a deep copy relationship. At this time, the existence of obj in the Map will not be processed by the garbage collection mechanism. At this time, if we want to clear the reference object of this obj in the Map, we can use WeakMap.

Back to the topic, WeakMap is a kind of weakly referenced hash table object, just like the above example, if the key object is no longer referenced, it will be garbage collected and automatically deleted from WeakMap, thus avoiding the problem of memory leaks

features

  1. Key names can only be objects
  2. Key names use weak references

properties and methods

Create and initialize

This is similar to Map, except that the key name can only be passed to the object type

let obj: any = {
    name: "阿黄"
}
const weakMap = new WeakMap([[obj, "阿黄"]]);

other properties

WeakMap only has the get, set, has, and delete methods of Map, and does not include the iterator iteration attribute, which means that clear needs to be manually deleted one by one.

const obj = {
    name: "阿黄"
}
const obj2 = {
    name: "小黑"
}
const weakMap = new WeakMap([[obj, "阿黄"]]);
weakMap.set(obj2, "小黑")
weakMap.delete(obj)
console.log(weakMap.has(obj)); // false
console.log(weakMap.get(obj2)); // 小黑

scenes to be used

property privatization

Use WeakMap to encapsulate the properties of the class

const animalPrivate = new WeakMap()
class Animal {
    constructor() {
        animalPrivate.set(this, {
            name: "阿黄"
        })
    }
    getName() {
        return animalPrivate.get(this).name
    }
}

console.log(new Animal().getName());

avoid memory leaks

Different from the Map effect, the weakMap key name will also be deleted after the associated object is deleted

let obj: any = {
    name: "阿黄"
}
const weakMap = new WeakMap([[obj, "阿黄"]]);
console.log(weakMap.get(obj)); // 阿黄
obj = null
console.log(weakMap.get(obj)); // undefined

WeakSet

WeakSet, like WeakMap, can also avoid memory leaks, and each of its items can only pass object types

features

  1. Values ​​can only be objects
  2. Values ​​use weak references

properties and methods

Create and initialize

const obj = {
    name: "阿黄"
}
const weakSet = new WeakSet([obj]);

other properties

WeakSet is also a simplified version of Set. It only has three attributes: add, delete, and has. Like WeakMap, it does not support the iterator attribute and cannot be iterated.

const obj = {
    name: "阿黄"
}
const obj2 = {
    name: "小黑"
}
const weakSet = new WeakSet([obj]);
weakSet.add(obj2)
weakSet.delete(obj)
console.log(weakSet.has(obj));// false

scenes to be used

avoid memory leaks

This is the same as WeakMap

let obj: any = {
    name: "阿黄"
}
const weakSet = new WeakSet([obj]);
obj = null
console.log(weakSet.has(obj));// false

Summarize

This article mainly introduces four new data structures introduced by ES6, namely Map (mapping), Set (collection), WeakMap (weak mapping) and WeakSet (weak collection). Map keys can be of any type, unique and ordered; Set keys and values ​​can be combined and can be any value, unique and disordered; WeakMap is a youth version of Map whose keys are limited to objects; WeakSet is a mini version of Set whose values ​​are objects. The keys of Weak and the two disappear immediately after being garbage collected.

The above is the entire content of the article. If the article is helpful to you or you think the article is good, please support the author, thank you!

Guess you like

Origin blog.csdn.net/time_____/article/details/130285260