欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解ES6?中的迭代器和生成器

 更新時間:2022年08月06日 15:36:44   作者:紫青寶劍  
迭代器是一個統(tǒng)一的接口,它的作用是使各種數(shù)據(jù)結(jié)構(gòu)可以被便捷的訪問,它是通過一個鍵為Symbol.iterator的方法來實現(xiàn),這篇文章主要介紹了ES6?中的迭代器和生成器,需要的朋友可以參考下

1.迭代器

Iterator是 ES6 引入的一種新的遍歷機制。兩個核心

  • 迭代器是一個統(tǒng)一的接口,它的作用是使各種數(shù)據(jù)結(jié)構(gòu)可以被便捷的訪問,它是通過一個鍵為Symbol.iterator的方法來實現(xiàn)。
  • 迭代器是用于遍歷數(shù)據(jù)結(jié)構(gòu)元素的指針(如數(shù)據(jù)庫中的游標(biāo))。
// 使用迭代
// 1.使用Symbol.iterator創(chuàng)建一個迭代器
const items = ['one','a','b'];
const it = items[Symbol.iterator]();
console.log(it);// Array Iterator{}
// 2.調(diào)用next()方法向下迭代,next()返回當(dāng)前的位置
const nx = it.next();
// 3.當(dāng)done為true的時候遍歷結(jié)束。
console.log(nx); // {value: 'one', done: false}

可迭代的數(shù)據(jù)結(jié)構(gòu)Array,String,Map,Set;

注意:對象不能使用迭代,跟迭代緊密相關(guān)的就是for..of循環(huán)。

對象轉(zhuǎn)換為數(shù)組使用相關(guān)的for..of循環(huán)。

// 對象轉(zhuǎn)換為數(shù)組
const arrlink = {"length":3,0:"zero","1":"one"};// 注意,第一項為聲明數(shù)組的長度,如果沒有第一項,則為空數(shù)組
console.log(Array.from(arrlink)); // (3) ['zero', 'one', undefined] 輸入?yún)?shù)的長度應(yīng)為去除第一項后,超出將默認值位undefined
for (let item of Array.from(arrlink)){
    console.log(item);// 遍歷的結(jié)果為,對象的值 zero ,one ,undefined.
}

2.生成器

ES6 新引入了Generator函數(shù),可以通過關(guān)鍵字yield把函數(shù)流程掛起,(與 Python 中的生成器相似)。

為改變執(zhí)行流程提供了可能,從而也為異步編程提供了解決方案(類似于Python中使用該函數(shù)實現(xiàn)協(xié)程的相似)。

與普通函數(shù)的區(qū)分:

  • function后面,函數(shù)名之前有個*
  • 函數(shù)內(nèi)部有yield(產(chǎn)出)表達式。
// 注意格式 函數(shù)關(guān)鍵字后面有 *
function* func(a){
    console.log("one");
    yield a;
    console.log("two");
    yield 2;
    console.log("three");
    return 3;
}
 
// 每一次執(zhí)行函數(shù)都會返回一個遍歷器對象
let fn = func(1);
console.log(fn);// func{<suspended>}
// 必須調(diào)用遍歷器的next()方法使指針下移到下一個狀態(tài)。
console.log(fn.next());// {value: 1, done: false}
console.log(fn.next());// {value: 2, done: false}
console.log(fn.next());// {value: 3, done: true}
console.log(fn.next());// {value: undefined, done: true}

總結(jié):Generator函數(shù)是分段執(zhí)行的,yield語句是暫停執(zhí)行,next方法可以恢復(fù)執(zhí)行。

function* add() {
    console.log('start');
    let x = yield '2';
    console.log('one:' + x);//20
    let y = yield '3';
    console.log('two:' + y);//30
    console.log('total:' + (x + y));// 50
    return x+y;
}
var a = add();
console.log(a.next(10));
console.log(a.next(20));
console.log(a.next(30));
// console.log(a.return(100));

return方法返回給定值,并結(jié)束遍歷Generator函數(shù)。提供返回的參數(shù),返回指定的值,不提供,返回undefined.

// 使用場景,為不具備Interator接口的對象提供了遍歷操作
function* objectEntries(obj) {
    // 獲取對象的所有key 存儲到數(shù)組中
    const propKeys = Object.keys(obj);
    // console.log(propKeys);
    for (const propKey of propKeys) {
        yield [propKey, obj[propKey]];
    }
}
 
const obj = {
    name: 'Jane',
    age: 18
}
 
obj[Symbol.iterator] = objectEntries;
console.log(obj);
 
for (const [key, value] of objectEntries(obj)) {
    console.log(`${key}: ${value}`);
}

生成器的應(yīng)用:

// ajax是典型的異步操作.通過Generator函數(shù)部署Ajax操作,可以用同步的方式表達
function* main() {
    const res = yield request(
        'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
    );
    console.log(res);
    console.log('1111');
}
let it = main();
it.next()
 
// https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976
function request(url) {
    // 假設(shè)
    $.ajax({
        url,
        method: 'get',
        success(res) {
            // it.next(res);
            it.next(res);
 
        }
    })
}
 
// Generator 函數(shù)用來處理異步操作
function* load() {
    loadUI();
    yield showData();
    hideUI();
}
 
let itLoad = load();
// console.log(itLoad);
//  第一次調(diào)用會顯示加載UI界面,并且異步的加載數(shù)據(jù)
itLoad.next();
function loadUI() {
    console.log('加載loading界面.....');
}
function showData(){
    setTimeout(() => {
        console.log('數(shù)據(jù)加載完成.....');
        //  第二調(diào)用,會調(diào)用hideUI(),隱藏Loading
        itLoad.next();
    }, 1000);
 
}
function hideUI() {
    console.log('隱藏loading....');
}
 
// 給任意對象部署Interator接口

到此這篇關(guān)于詳解ES6 中的迭代器和生成器的文章就介紹到這了,更多相關(guān)ES6 迭代器和生成器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論