您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“ES6中的迭代器和生成器怎么使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“ES6中的迭代器和生成器怎么使用”吧!
Iterator
是 ES6 引入的一種新的遍歷機(jī)制。兩個(gè)核心
迭代器是一個(gè)統(tǒng)一的接口,它的作用是使各種數(shù)據(jù)結(jié)構(gòu)可以被便捷的訪問,它是通過一個(gè)鍵為Symbol.iterator
的方法來實(shí)現(xiàn)。
迭代器是用于遍歷數(shù)據(jù)結(jié)構(gòu)元素的指針(如數(shù)據(jù)庫中的游標(biāo))。
// 使用迭代 // 1.使用Symbol.iterator創(chuàng)建一個(gè)迭代器 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的時(shí)候遍歷結(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"};// 注意,第一項(xiàng)為聲明數(shù)組的長度,如果沒有第一項(xiàng),則為空數(shù)組 console.log(Array.from(arrlink)); // (3) ['zero', 'one', undefined] 輸入?yún)?shù)的長度應(yīng)為去除第一項(xiàng)后,超出將默認(rèn)值位undefined for (let item of Array.from(arrlink)){ console.log(item);// 遍歷的結(jié)果為,對象的值 zero ,one ,undefined. }
ES6 新引入了Generator
函數(shù),可以通過關(guān)鍵字yield
把函數(shù)流程掛起,(與 Python 中的生成器相似)。
為改變執(zhí)行流程提供了可能,從而也為異步編程提供了解決方案(類似于Python中使用該函數(shù)實(shí)現(xiàn)協(xié)程的相似)。
與普通函數(shù)的區(qū)分:
在function
后面,函數(shù)名之前有個(gè)*
;
函數(shù)內(nèi)部有yield
(產(chǎn)出)表達(dá)式。
// 注意格式 函數(shù)關(guān)鍵字后面有 * function* func(a){ console.log("one"); yield a; console.log("two"); yield 2; console.log("three"); return 3; } // 每一次執(zhí)行函數(shù)都會返回一個(gè)遍歷器對象 let fn = func(1); console.log(fn);// func{<suspended>} // 必須調(diào)用遍歷器的next()方法使指針下移到下一個(gè)狀態(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操作,可以用同步的方式表達(dá) 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接口
到此,相信大家對“ES6中的迭代器和生成器怎么使用”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。