-
可用于迭代的数据结构
- 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 创建,不可迭代
-