ES6 iterators, Sets, Map collections and async asynchronous functions

Table of contents

Iterator

The role of Iterator

The traversal process of Iterator

 Set

 Map collection

 What is the difference between map and object?

async asynchronous function


Iterator

Iterator (Iterator) is such a mechanism. It is an interface that provides a unified access mechanism for various different data structures. As long as any data structure deploys the Iterator interface, it can complete the traversal operation (that is, process all members of the data structure in sequence).

The role of Iterator

Provide a unified and simple access interface for various data structures;

Enables the members of a data structure to be arranged in a certain order;

ES6 created a new traversal command for...of loop, and the Iterator interface is mainly used for consumption by for...of.

The traversal process of Iterator

  1. Creates a pointer object pointing to the starting position of the current data structure. In other words, the traverser object is essentially a pointer object.

  2. The first time you call the next method of a pointer object, you can point the pointer to the first member of the data structure.

  3. The second time the next method of the pointer object is called, the pointer points to the second member of the data structure.

  4. Keep calling the next method of the pointer object until it points to the end of the data structure.

/**
 * 数组 keys values entries
 * 方法全部返回迭代器对象 就可以使用 for of遍历
 * 迭代器接口本质就是调用迭代器对象的next方法   指针 
 *          调用next方法会依次指向内部成员
 */
let arr = [1,2,3,4,5];
let keys = arr.keys();
let values = arr.values();
let entries = arr.entries();
console.log(keys.next());   //{ value: 0, done: false }
console.log(keys.next());   //{ value: 1, done: false }
console.log(keys.next());   //{ value: 2, done: false }
console.log(keys.next());   //{ value: 3, done: false }
console.log(keys.next());   //{ value: 4, done: false }
console.log(keys.next());   //{ value: undefined, done: true }
// console.log(values.next());
// console.log(entries.next());
// let result;
// while(!(result = keys.next()).done){
//     console.log(result.value);  //这里用keys.next() 会再次执行一次
// }


console.log(keys,values,entries);
for(let key of keys){
    console.log(key,'key');
}
for(let value of values){
    console.log(value,'value');
}
for(let entry of entries){
    console.log(entry,'entry');
}

function test(){
    // arguments 是迭代器对象
    for(let key of arguments){
        console.log(key);
    }
}
test('1','2',3,4,5)

 The data structures with native Iterator interface are as follows:
    Array, Map, Set, String, TypedArray, arguments, NodeList 

We can also turn the data type that was not iterable into iterable, so that it can support for...of loops, such as objct! If we directly execute for...of on the object, an error will definitely occur:


let obj = {
    name:'zhangsan',
    age:12
}

for(let key of obj){         //报错 obj is not iterable
    console.log(key);
}

let obj = {
    name:'zhangsan',
    age:12
}

// for(let key of obj){         //报错 obj is not iterable
//     console.log(key);
// }
let keys = Object.keys(obj);
console.log(keys);
for(let key of keys){
    console.log(key);
}

 Set

Set is similar to an array, but the values ​​of its members are unique and there are no duplicate values. Set itself is a constructor used to generate the Set data structure. The Set constructor can accept an array (or other data structure with an iterable interface) as a parameter for initialization.

/**
 * set集合
 *  特点:内部成员值是唯一的
 *  参数:无或者实现了迭代器接口的数据结构 数组 字符串
 * 创建使用set构造函数 new Set() typeof
 */
let set = new Set();
// console.log(set,typeof(set),set instanceof Object);
// 添加内部成员 add
// 注意:如果是基本数据类型相同的值添加两次会自动去重 
//      如果是引用数据类型 会添加多次 (引用地址不同)
set.add('hello');
set.add('world');
set.add('hello');
let arr1 = [];
set.add(arr1);
set.add([]);
console.log(set);

// 删除内部成员delete
// 注意:删除引用数据类型的时候如果是内容则无法删除 是指向地址的变量则可以删除
set.delete([]); //无法删除
set.delete(arr1);   //可以删除
console.log(set);

// 遍历set集合
console.log(set.keys());
console.log(set.values());
console.log(set.entries());
for(let key of (set.keys())){
    console.log(key);
}
set.forEach((key,value)=>{
    console.log(key,value);
})

/**
 * has 检验set集合有没有该内部成员
 * 引用数据类型最好放引用地址
 */
console.log(set.has('hello'));
console.log(set.has([]));

/**
 * 属性
 * 查看set内部成员个数 size
 */
console.log(set.size);
let obj = {};
set.add(obj);
console.log(set.size);

/**
 * 应用 数组去重 set
 */
let set1 = new Set([1,2,3,4,3,2,1]);
console.log(set1);
let res1 = Array.from(set1);
console.log(res1);
console.log(set1[0]);
let res2 = Array.prototype.slice.call(set1,0);
console.log(res2);

let res3 = [...set1];
console.log(res3);

let set2 = new Set('hello');
console.log(set2);

 Map collection

Map is similar to an object and is also a collection of key-value pairs, but the scope of "keys" is not limited to strings. Various types of values ​​(including objects) can be used as keys. In other words, the Object structure provides "string-value" correspondence, and the Map structure provides "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value pair" data structure, Map is more suitable than Object. Map can accept an array as parameter. The members of this array are arrays representing key-value pairs.

/**
 * 键值对的一种数据结构 键可以是任意数据类型
 */
let obj = {
    name:'zhangsan',
    age:12,
    [Symbol('email')]:"[email protected]",
}
obj[{}] = 1;        //期望出现{} =>1 结果出现'[object Object]' => 1
let res = Object.entries(obj);
let map = new Map(res);
console.log(map,typeof map,map instanceof Object);
map.set({},1);
map.set([],function(){});
map.set(undefined,'hello');
console.log(map);
/**
 * 遍历map keys values entries forEach
 */
console.log(map.keys());
console.log(map.values());
console.log(map.entries());

for(let key of map){
    console.log(key,'22222');
}

map.forEach((key,value)=>{
    console.log(key,value);
})

map.forEach((key,value)=>{
    console.log(value,key,'value是值,key是键');
})

console.log(map.size);
// 删除某一个属性
map.delete('name');
console.log(map);
// 获取属性键对应的值
console.log(map.get('age'));
console.log(Map.prototype);
console.log(Set.prototype);

 

 What is the difference between map and object?

    1. The map key can be any data type, and the object key can only be a string or symbol value.
    2. The map can be traversed using for...of, which implements the iterator interface.
    3. The object can only be traversed using the for in loop because it is not implemented. Iterator interface
    4.map can directly call the forEach method to traverse
    5.The number of key-value pairs of map can be obtained directly through the size attribute, and the object needs to be obtained manually
    6.map is more suitable for key-value pairs, and some optimizations have been made for frequent deletion of map
    7. The internal key-value pairs of the map are ordered, but the object attributes are unordered.

async asynchronous function

An async function is a function declared using the async keyword. An async function is an instance of the AsyncFunction constructor, and the await keyword is allowed within it. The async and await keywords allow us to write Promise-based asynchronous behavior in a more concise way without deliberately chaining promises.

The await keyword is only valid within async functions. If you use it outside the body of an async function, a SyntaxError will be thrown. The purpose of async/await is to simplify the syntax required when using promise-based APIs. async/await behaves like a combination of generators and promises. The async function must return a promise object. If the return value of an async function does not appear to be a promise, it will be implicitly wrapped in a promise.

Simply put, it is a function, which is an asynchronous programming solution. It encapsulates the generator function internally, which is a syntactic sugar. It has its own executor and is used in conjunction with await; asynchronous programming and synchronous processing.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
</head>

<body>
    <script>
        async function getFindAll() {
            try {
                let res = await axios.get('http://121.199.0.35:8888/index/carousel/findAll');
                console.log(res);
            } catch {
                throw new Error('请求失败')
            } finally {
                console.log('请求完成');
            }
        }
        getFindAll();
    </script>
</body>

</html>

 

 

Guess you like

Origin blog.csdn.net/qq_53866767/article/details/131749775