Winter vacation study-ES6 (3)

Winter vacation study-ES6 (3)

Iterator

Any data structure can be traversed by deploying the iterator interface

  • for ofcycle
  • Native data with this interface (available for of traversal)
    • Array
    • Arguments
    • Set
    • Map
    • String
    • TypedArray
    • NodeList

for in saves the key name, for of saves the key value

  • Principle: Create a pointer object to point to the starting position of the array, the first time the next method is called, the pointer points to the first member, and then move one by one to traverse until the last member
  • 每次调用next方法的时候会返回一个包含value和done两个属性的对象
 <script>
            const fruit=['猕猴桃','菠萝蜜','香蕉'];
            let iterator=fruit[Symbol.iterator]();
            console.log(iterator.next());
    </script>

Iterator example (custom data traversal)

 <script>
        const studio = {
            name: 'homyit',
            member: ['3qq', 'hh', 'll', 'tt', 'db', 'xx', ],
            [Symbol.iterator]() {
                let index = 0;
                let _this = this; //因为如果直接用this的话它的作用域是return那个大括号而不是整个这个对象,所以要用一个临时变量保存一下或者用箭头函数也行
                return {
                    //要返回一个next方法一个value属性,一个done属性
                    next: function () {
                        if (index < _this.member.length) {
                            const result = {
                                value: _this.member[index],
                                done: false
                            }
                            index++;
                            return result;
                        } else {
                            return {
                                value: undefined,
                                done: true
                            };
                        }
                    }
                }
            }
        }

        //对对象的那个成员属性进行遍历
        for(let i of studio){
            console.log(i);
        }
    </script>

Builder

  • Essence: is a special function
  • Role: asynchronous programming
  • Declaration form:function * 函数名(参数){函数体}
  • The execution statement is directly called and will not be executed through the next method
  • Function code separator: yeild statement, followed by + expression or argument, divide the function into several sections, and use next several times to execute them.
<script>
        function * gen(){
            console.log("第一个代码段");
            yield '1';
            console.log("第二个代码段");
            yield '2';
            console.log("第三个代码段");
            yield '3';
            console.log("第四个代码段");

        }
        let iterator=gen();
        //console.log(iterator);//返回一个迭代器对象
        iterator.next();//四次调用next分别输出四个代码段的输出语句内容
        iterator.next();
        iterator.next();
        iterator.next();
    </script>

If you call next alone, the content of the delimited code segment will be output. If you print the next method, you will find that the value of the next method is the content of the yeild statement

  • Generator parameters:
    • The next parameter is used as the return value of the previous yeild statement
<script>
        function * gen(args){
            console.log(args);
            let one=yield '第一个';
            console.log(one);
            let two=yield '第二个';
            console.log(two);

        }
        let ite=gen('aaa');//可以打印出实参
        ite.next();
        ite.next("第一个yeild语句的返回值");
        ite.next("第二个yeild语句的返回值");
    </script>
  • Generator instance
  <script>
        //异步编程 文件操作 网络操作(ajax request) 数据库操作
        //实现1s后控制台输出111,2s后控制台输出222,3s后控制台输出333
        //本来是三层回调现在可以借助内嵌next方法实现
        function one(){
            setTimeout(()=>{
                console.log(111);
                ite.next();
            },1000)
        }
        function two(){
            setTimeout(()=>{
                console.log(222);
                ite.next();
            },2000)
        }
        function three(){
            setTimeout(()=>{
                console.log(333);
                ite.next();
            },3000)
        }
        function *gen(){
            yield one();
            yield two();
            yield three();
        }
        let ite=gen();
        ite.next();
    </script>

Promise

  • Essence: a constructor can instantiate objects
  • Role: used to encapsulate asynchronous operations and get the results of their success or failure
  • then method: if the state is successful, call the first callback function of the parameter, if it fails, call the second
<script>
        const p = new Promise(function (resole, reject) {

            setTimeout(function () {
                // let data = '用户数据';
                //     resolve (data);//让promise状态变成成功,通过then的第一个方法提取数据

                let err='数据读取失败';
                reject(err);//调用第二个函数参数

            }, 1000);
        }); //传入一个函数作为参数

        //调用promise对象的then方法,两个函数参数,如果上面调用了resolve这里就会执行then的第一个函数参数
        p.then(function (value) {
            console.log(value);
        }, function (reason) {
            console.log(reason);
        })
    </script>
  • Proomise package read file
const fs=require('fs');
//两个参数一个路径一个函数
fs.readFile('./好好学习.md',(err,data)=>{
        if(err) throw err;
        console.log(data.toString());
});

//用Promise封装
const p=new Promise(function(resolve,reject){
        fs.readFile("./好好学习.md",(err,data)=>
        {
            //如果失败
            if(err) reject(err);
            //如果成功
            resolve(data);
        });

});
//通过then方法来指定回调
p.then(function(value){
console.log(value.toString());
},function(reason){
    console.log("读取文件失败");
});
  • Promise encapsulation AJAX
 <script>
        const p = new Promise((resolve, reject) => {
            //1.创建对象
            const xhr = new XMLHttpRequest();

            //2.初始化
            xhr.open("GET","https://api.apiopen.top/getJoke");
            //3.发送
            xhr.send();
            //4.绑定事件,处理响应结果
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    //判断响应状态码
                    if (xhr.status >= 200 && xhr.status < 300) {//表示成功
                        resolve(xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            }
        });


        p.then(function (value) {
            console.log(value);
        }, function (reason) {
            console.error(reason);
        })
    </script>
  • Promise's then method analysis
    • 1. If the result returned in the callback function is a non-promise object (including undefined if there is no return value), the status is success, and the return value is the non-promise object
    • 2. Is a Promise object that returns the content of the object
    • 3. Throw an error:
 <script>
        const p=new Promise((resolve,reject)=>{
            setTimeout(() => {
               // resolve("用户数据");
               reject('出错啦');
            }, 1000);
        });

        //调用then方法,该方法返回的值是Promise对象,对象状态由回调函数的执行结果决定

        const result=p.then(value=>{
            console.log(value);
            //return 'honghong'

            return new Promise((resolve,reject)=>{
                reject('error');
            })//如果then方法中的参数函数返回的是promise对象
            // throw new Error('出错了哦');
        },reason=>{
            console.warn(reason);
        })
        console.log(result);
    </script>
  • Because the then method returns a Promise, it can be called in a chain
 p.then(value=>{},reason=>{}).thenthen(value=>{},reason=>{})

Collection and API

  • Set collection
  • Essence: is a new data structure similar to an array
  • Implemented the iterator interface can be traversed with spread operator and for of
  • Properties and methods:
    • size: returns the number of elements, equivalent to the length of the array
    • add: add a new element to return to the current collection
    • delete: delete the element and return the boolean value
    • has: check whether it contains an element, return a boolean
 <script>
        let s = new Set(); //可传参或者不传参
        let s2 = new Set(['apple', 'banana', 'apple']);
        console.log(s2);//会进行去重与数学中集合概念很像
        s2.add('orange');//同理可以对其他几个属性进行测试
    </script>
  • example
<script>
        //数组去重
       let arr1=['红红','橙橙','黄黄','绿绿','红红'];
        let result=[...new Set(arr1)];//数组
        console.log(result);

        //找交集
        let arr2=['橙橙','黄黄','绿绿','蓝蓝'];
        let result2=[...new Set(arr1)].filter(item=>{
           let s2=new Set(arr2);
           if(s2.has(item)){
               return true;
           }else{
               return false;
           }
        });
        console.log(result2);
        
        
    </script>

Map

  • Essence: A new data structure is a collection of key-value pairs. The keys can be various types of values ​​and objects can also be
  • The iterator interface is implemented, so the spread operator and for of can also be used to traverse
  • Related attributes and methods:
  • Insert picture description here

Guess you like

Origin blog.csdn.net/Phoebe4/article/details/113486984