ES6——迭代器
阿新 • • 發佈:2020-08-02
-
可用於迭代的資料結構
- Array
- String
- Map
- Set
- arguments
- Dom(正在進行中)
-
迭代器
-
Iterator
Iterator 是 ES6 引入的一種新的遍歷機制,迭代器有兩個核心概念
- 迭代器是一個統一的介面,它的作用是使各種資料結構可被便捷的訪問,它是通過一個鍵為 Symbol.iterator 的方法來實現
- 迭代器是用於遍歷資料結構元素的指標(如資料庫中的遊標)
Array
const items = ['zero','one','two'] const it = items[Symbol.iterator]() it.next() //{value:'zero', done: false} it.next() //{value:'one', done: false} it.next() //{value:'two', done: false} it.next() //{value:undefined, done:true}
Map
let myMap = new Map() myMap.set(0,'zero') myMap.set(1,'one') myMap.set(2,'two') const mapIt = myMap[Symbol.iterator]() mapIt.next() //{value: [0,'zero'], done: false} mapIt.next() //{value: [1,'one'], done: false} mapIt.next() //{value: [2,'two'], done: false} mapIt.next() //{value: undefined, done: true}
Set
let mySet = new Set() mySet.add('zero') mySet.add('one') mySet.add('two') const setIt = mySet[Symbol.iterator]() setIt.next() //{value:'zero', done:false} setIt.next() //{value:'one', done:false} setIt.next() //{value:'two', done:false} setIt.next() //{value:undefined, done:true}
String
let str = 'hello' const strIt = str[Symbol.iterator]() strIt.next() //{value:'h', done:false} strIt.next() //{value:'e', done:false} strIt.next() //{value:'l', done:false} strIt.next() //{value:'l', done:false} strIt.next() //{value:'o', done:false} strIt.next() //{value:undefined, done:true}
-
for...of
ES6 新引入的迴圈,用於代替 for...in 和 forEach(),並且支援新的協議。它可用於迭代常規的資料型別,如 Array、String、Map、Set 等等
Array
const items = ["zero","one","two"] for(let item of items){ console.log(item) } // zero // one // two
Map
let myMap = new Map() myMap.set(0,'zero') myMap.set(1,'one') myMap.set(2,'two') for(let item of myMap){ console.log(item) } //[0,'zero'] //[1,'one'] //[2,'two']
Set
let mySet = new Set() mySet.add('zero') mySet.add('one') mySet.add('two') for(let item of mySet){ console.log(item) } //zero //one //two
String
let str = 'hello' for(let s of str){ console.log(s) } //h //e //l //l //o
注:普通物件是由 Object 建立,不可迭代
-