ES6之遍历器iterator的介绍(含for ... of )

一、遍历器

定义:它是一种接口,为各种不同的数据结构提供统一的访问机制。
作用:任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员),Iterator 接口的目的,就是为所有数据结构,提供了一种统一的访问机制,即for…of循环

以下的类型具有iterator遍历器接口
Array
Map
Set
String
TypedArray
函数的 arguments 对象
NodeList 对象

二、实际应用场合
1.解构赋值

let set = new Set().add('a').add('b').add('c');

let [x,y] = set;
// x='a'; y='b'

let [first, ...rest] = set;
// first='a'; rest=['b','c'];

2、拓展运算符

var str = 'hello';
[...str] //  ['h','e','l','l','o']

// 例二
let arr = ['b', 'c'];
['a', ...arr, 'd']
// ['a', 'b', 'c', 'd']

由于数组的遍历会调用遍历器接口,所以任何接受数组作为参数的场合,其实都调用了遍历器接口。下面是一些例子。

for…of
Array.from()
Map(), Set(), WeakMap(), WeakSet()(比如new Map([[‘a’,1],[‘b’,2]]))
Promise.all()
Promise.race()

3、for … of 应用iterator
(1)、数组
数组拥有原生的iterator接口

var arr = ['a', 'b', 'c', 'd'];

for (let a in arr) {
  console.log(a); // 0 1 2 3
}

(2)、Set和Map
Set 和 Map 结构也原生具有 Iterator 接口,可以直接使用for…of循环。

var engines = new Set(["Gecko", "Trident", "Webkit", "Webkit"]);
for (var e of engines) {
  console.log(e);
}
// Gecko
// Trident
// Webkit

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
// committee: TC39
// standard: ECMA-262

4、for…of 和for …in
for…of可以遍历所有拥有遍历器接口(iterator)的数据结构,Set,Map,Array等,按顺序输出属性名。
for…in是精准的迭代语言,可以用来枚举对象属性,但是输出的属性名是无序的。

猜你喜欢

转载自blog.csdn.net/qq_36470086/article/details/82393291