Iterator、for..of,for...in和自定义遍历器
- Iterator:
var arr = [1,2,3,4,5]; var ite = arr[Symbol.iterator](); console.log(ite.next()); console.log(ite.next()); console.log(ite.next()); console.log(ite.next()); console.log(ite.next()); console.log(ite.next()); //依次打印:Object {value: 1, done: false}; Object {value: 2, done: false}; Object {value: 3, done: false}; Object {value: 4, done: false}; Object {value: 5, done: false}; Object {value: undefined, done: true}.注释:1.Iterator就是一个指针; 2.指针默认在-1的位置; 3.没有遍历完的时候done的值是false,遍历完了就是true; 4.意义:提高具有遍历接口数据的效率; 5.特点:它用来访问具有遍历接口数据,有一个next方法(指针).
for..of,for...in:
普通数组遍历:
let arr = [1,2,3,4,5]; for(let item of arr){ console.log(item); } //输出:1 2 3 4 5。
迭代器遍历:
let iterator = arr[Symbol.iterator](); let result = iterator.next(); while(!result.done){ console.log(result.value); result=iterator.next(); } //输出 1 2 3 4 5。
数组 Set Map
var s = new Set([1,2,3]); console.log(s);//打印:Set(3) {1, 2, 3}; var itera = s[Symbol.iterator](); console.log(itera.next());//打印:Object {value: 1, done: false}; var m = new Map([["age",21],["sex","男"]]); m.set("name","曹伟"); console.log(m);//打印:Map(3) {"age" => 21, "sex" => "男", "name" => "曹伟"}; var i = m[Symbol.iterator](); console.log(i.next());//打印:Object {value: Array(2), done: false}; let obj = {x:1,y:2,z:3}; let arr = ['a','b','c']; for(let key in obj){ console.log(key);//打印:x y z; console.log(obj[key]);//打印:x 1 y 1 z 1; } for(let key in arr){ console.log(key);//打印:x y z; console.log(arr[key]);//打印:x 1 y 1 z 1; }注释:1.遍历对象用forin,遍历数组,Map,Set,类数组用for of。 2.for in可以遍历对象,也可以遍历数组.
- 自定义遍历器:
```
var arr = [1,2,3,4,5]; function Iterator(arr){ let i = -1; //遍历器默认指在-1的位置; function next(){ //返回一个方法; i++; //当next的时候,i向后移; let value; //声明一个空的变量; let done = flase; //done的默认值是没有遍历完成; if(i == arr.length){ //如果i等于数组的长度的时候,i就溢出了,所以value的值是undefined,done的值是true; value = undefined; done = true; }else{ //否则value的值就等于数组中的值; value=arr[i]; } return {value:value,done:done}; //返回两个值,一个值是value,另一个值是done; } return {next:next}; //返回next方法; }var ite = arr[Symbol.iterator]();console.log(ite.next());console.log(ite.next());console.log(ite.next());console.log(ite.next());console.log(ite.next());console.log(ite.next());依次打印:Object {value: 1, done: false}; Object {value: 2, done: false}; Object {value: 3, done: false}; Object {value: 4, done: false}; Object {value: 5, done: false}; Object {value: undefined, done: true}.