本文實(shí)例講述了ES6 Iterator接口和for...of循環(huán)用法。分享給大家供大家參考,具體如下:
<script>// 數(shù)組已經(jīng)幫我們內(nèi)置這個(gè)Iterator接口let arr = ['hello','world'];let map = arr[Symbol.iterator](); // 數(shù)組直接調(diào)用iterator接口,返回一個(gè)對(duì)象mapconsole.log(map.next()); // {value: "hello", done: false} done:循環(huán)沒有下一步狀態(tài):true沒有,false:有狀態(tài),循環(huán)并沒有結(jié)束console.log(map.next()); // {value: "world", done: false}console.log(map.next()); // {value: undefined, done: true}</script>運(yùn)行結(jié)果:

for...of循環(huán),就是不斷的調(diào)用Iterator接口。
object數(shù)據(jù)結(jié)構(gòu)沒有實(shí)現(xiàn)Iterator接口。
自定義實(shí)現(xiàn)object的Iterator接口
<script>let obj ={ start: [1,5,7], end:[8,4,3], [Symbol.iterator](){ let self = this; let index = 0; let arr = self.start.concat(self.end); let len = arr.length; return { next(){ if(index<len){ return{ value:arr[index++], done:false } }else{ return { value:arr[index++], done:true } } } } }}for(let key of obj){ // for...of 背后用的就是iterator接口 console.log(key); // 1 5 7 8 4 3}</script>運(yùn)行結(jié)果:

<script>let arr = ['xixiaoxian','jamin'];for(let value of arr){ console.log(value); // xixiaoxian jamin}</script>運(yùn)行結(jié)果:

感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.VeVB.COm/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注