技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

ES6入門教程之Iterator與for...of循環(huán)詳解

來源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2017-10-24 18:28┆點(diǎn)擊:

一、Iterator(遍歷器)

遍歷器(Iterator)是一種協(xié)議,任何對象只要部署了這個(gè)協(xié)議,就可以完成遍歷操作。在ES6中遍歷操作特質(zhì)for….of循環(huán)。

它的作用主要有兩個(gè):

為遍歷對象的屬性提供統(tǒng)一的接口。

使對象的屬性能夠按次序排列。

ES6的遍歷器協(xié)議規(guī)定,部署了next方法的對象,就具備了遍歷器功能。next方法必須返回一個(gè)包含value和done兩個(gè)屬性的對象。value屬性是當(dāng)前遍歷的位置的值,而done屬性是一個(gè)布爾值,用來表示遍歷是否結(jié)束。

function makeIterator(array) { var nextIndex = 0; return { next: function() { return nextIndex < array.length ? {value: array[nextIndex++], done: false} : {value: undefined, done: true}; } } } var it = makeIterator(['a', 'b']); it.next().value; //'a' it.next().value; //'b' it.next().done; // true

在上面代碼片段中,定義了一個(gè)makeIterator函數(shù),它的作用是返回一個(gè)遍歷器對象,用來遍歷參數(shù)數(shù)組。特別需要注意的是next返回值的構(gòu)造。

下面,再看看一個(gè)遍歷器的示例代碼片段:

function idMaker() { var index = 0; return { next: function() { return {value: index++, done: false}; } } } var it = idMaker(); it.next().value; //'0' it.next().value; //'1' it.next().value; //'2'

二、for…of 循環(huán)

在ES6中,一個(gè)對象只要部署了next方法,就被視為是具有了iterator接口,就可以用for…of循環(huán)遍歷它的值。

function idMaker() { var index = 0; return { next: function() { return {value: index++, done: false}; } } } for (var n of it) { if (n > 5) { break; console.log( n ); } } //0 //1 //2 //3 //4 //5

上面的代碼說明,for….of默認(rèn)從0開始循環(huán)。

數(shù)組原生具備iterator接口

const arr = [1, 5, 3, 9]; for (let v of arr) { console.log( v ); } //1 //5 //3 //9

相比較,Js原有的for…in循環(huán),只能獲得對象的鍵名,不能直接獲取鍵值。ES6提供了for…of循環(huán),允許遍歷獲取鍵值。

var arr = ['a', 'b', 'c', 'd']; for (a in arr) { console.log( a ); } //0 //1 //2 //3 for (a of arr) { console.log( a ); } //0 //1 //2 //3

上面的代碼片段表明,for…in循環(huán)讀取鍵名,而for…of循環(huán)讀取鍵值。

對于Set和Map結(jié)構(gòu)的數(shù)據(jù),可以直接使用for…of循環(huán)。

var name = ['S', 'D', 'J', 'Z', 'G', 'G', 'G']; for ( var e of name) { console.log( e ); } //S //D //J //Z //G var es6 = new Map(); es6.set('edition', 6); es6.set('committee', 'TC39'); es6.set('standard', 'ECMA-262'); for(var [name, value] of es6) { console.log(name + ": " + value); } // edition: 6 // commttee: TC39 // standard: ECMA-262

在上面的代碼片段中,演示了如何遍歷Set結(jié)構(gòu)和Map結(jié)構(gòu),后者是同是遍歷鍵名和鍵值。

對于普通的對象,for...of結(jié)構(gòu)不能直接使用,否則則會(huì)報(bào)錯(cuò)。必須項(xiàng)部署iterator接口才能使用。但是,在這種情況下,for...in循環(huán)依然可以遍歷鍵名。

var es6 = { name: "G.Dragon", year: 22, love: "coding" }; for (e in es6) { console.log( e ); } //name //year //love for( e of es6) { console.log( e ); } // TypeError: es6 is not iterable

最后,總結(jié)一下。for...of循環(huán)可以使用的范圍包括數(shù)組、類似數(shù)組的而對象(比如argument對象、DOM NodeList對象)、Set和Map結(jié)構(gòu)、后文的Generator對象,以及字符串。下面是使用for...of循環(huán)遍歷字符串和DOM NodeList對象的例子。

// 字符串例子 let str = "hello"; for (let s of str) { console.log( s ); } //h //e //l //l //o // DOM NodeList對象的例子 let paras = document.getSelectorAll("p"); for (let p of paras) { p.classList.add("test"); }