1.Iterator( 遍历器) 的概念
JavaScript 原有的表示“ 集合” 的数据结构, 主要是数组( Array) 和对象( Object), ES6 又添加了 Map 和 Set。 这样就有了四种数据集合, 用户还可以组合使用它们, 定义自己的数据结构, 比如数组的成员是 Map, Map 的成员是对象。 这样就需要一种统一的接口机制, 来处理所有不同的数据结构。
es6中新增了 for..of 循环
- 手写Iterator接口
const arr = [1,2,3];
function iterator(arr){
let index = 0;
return {
next : function(){
return index<arr.length?
{value:arr[index++],done:false}:
{value:undefind,done:true}
}
}
}
在 ES6 中, 有些数据结构原生具备 Iterator 接口( 比如数组), 即不用任何处理, 就可以被for…of循环遍历, 有些就不行( 比如对象)。 原因在于,这些数据结构原生部署了Symbol.iterator属性( 详见下文), 另外一些数据结构没有。 凡是部署了Symbol.iterator属性的数据结构, 就称为部署了遍历器接口。 调用这个接口, 就会返回一个遍历器对象。
2.具有Symbol.iterator 属性的数据结构都具有Iterator接口
const arr = [1,2,3];
const set = new Set([1,2,3]);
const map = new Map([[1,2],[3,4]]);
arr[Symbol.iterator]();
set[Symbol.iterator]();
map[Symbol.iterator]();
3.具备iterator接口的数据结构都可以进行如下操作
1.解构赋值
const set = new Set([1,2,3]);
let [x,y,z] = set;
console.log(x,y,z);
2.扩展运算符
let str = 'hongtao';
let arrStr = [...str];
利用set进行数组去重
const arr = [1,1,'a','b','a',2,1];
console.log([...new Set(arr)]);
3.for…of循环
const ofarr = [1,2,3,4];
for(let i of ofarr){
console.log(i);
}
const map = new Map();
map.set('a',1).set('b',2).set('c',3);
for(let data of map){
console.log(data)//['a',1].....
}
for(let [key,value] of map){
console.log(key,value);
}