《JavaScript高程》第七章

7.1理解迭代

计数就是最简单的迭代

  1. for(let i=0;i<10;i++){
  2. console.log(i);
  3. }

1、迭代之前要事先知道如何使用数据结构

2、遍历顺序不是数据结构固有的,也就是说通过索引来遍历数组不是固有的

7.2迭代器模式

可迭代对象是一种抽象的说法,基本上可以把可迭代对象理解为数组 Array 和集合 set 这样的数据类型

  1. let arr=[1,3,5,7,9];
  2. let stt=new Set().add(1).add)(5).add(7).add(9);
  3. for(let item of arr){
  4. console.log(arr); //返回 1 3 5 7 9
  5. }
  6. for(let item of stt){
  7. console.log(item); //返回 1 5 7 9
  8. }

可迭代对象不一定是集合对象,也可能是类似数组结构的可循环对象

例如 string :

  1. let str="String";
  2. for(let s of str){
  3. console.log(s); //返回 "S","t","i","n","g"
  4. }

7.2.1可迭代协议Iterable

包括1、字符串 2、数组 3、映射 4、集合 5、arguments对象 6、NodeList等DOM集合

可迭代对象的原生语言特性包括

for…of循环、数组解构、扩展操作符、Array.from()、创建集合、创建映射、Promise.all()、Promise.race()、yield *

for…of循环

  1. let str="string";
  2. for(let s of str){
  3. console.log(s); //返回 's','t','r','i','n','g';
  4. }

数组解构

例如,解构String

sample1解构字符串

  1. let str="String";
  2. let [a,b,c,d,e,f]=str;
  3. console.log(a); //返回 ‘S’
  4. console.log(b); //返回 ‘t’
  5. console.log(c); //返回 ‘r’
  6. ...

sample2解构数组

  1. let arr=[1,3,5];
  2. let [A,B,C]=arr;
  3. console.log(A); //返回 1
  4. console.log(B); //返回 3
  5. console.log(C); //返回 5

sample映射map

  1. let mp=new Map();
  2. mp.set(1,123);
  3. mp.set(2,234);
  4. let vals=mp.values;
  5. for(let item of vals){
  6. console.log(item); //返回
  7. }

set集合

  1. let st=new Set();
  2. st.add(1);
  3. st.add(2);
  4. st.add(3);
  5. let ent=st.entries(); //这里利用entries函数获取迭代对象
  6. for(let item of ent){
  7. console.log(item) //这里返回entries方法返回的是数组[value,value];
  8. }

arguments对象

  1. let func=function(val,cur,sum){
  2. let [a,b,c]=func.arguments;
  3. console.log(a);
  4. console.log(b);
  5. console.log(c);
  6. return a+b+c;
  7. }
  8. func(1,2,3); //输出 1 2 3 返回 1 + 2 + 3

7.3.1生成器

1、生成器的函数声明

只要在函数前面加个*号就可以定义一个生成器

  1. function *func(a,b){
  2. console.log(a);
  3. return a+b;
  4. }
  5. let f=func();
  6. console.log(f.next); //这里返回 ƒ next() { [native code] }

7.3.2 yield关键字,主要用于后台中

yield 关键字用来暂停和恢复一个生成器函数((function* 或遗留的生成器函数)。

yield相当于return,但不完全是return,弹出函数内部定义的值,遍历一遍之后就无法遍历了

  1. function *func(){
  2. let saleList=[1,3,5,7,9];
  3. for(let i=0;i<saleList.length;i++){
  4. yield saleList[i]
  5. }
  6. }
  7. let f1=func();
  8. console.log(f1.next().value); //返回 1
  9. console.log(f1.next().value);// 返回 {value: 3, done: false}
  10. for(let item of f1){
  11. console.log(item); //返回 5 7 9
  12. }
  13. console.log(f1.next()); //返回 {value: undefined, done: true}

#### 用yield写递归算法

  1. function *func(n){
  2. if(n>0){
  3. yield*func(n-1)
  4. yield(n-1)
  5. }
  6. }
  7. for(let x of func(4)){
  8. console.log(x); //返回 0 1 2 3 4
  9. }

7.3.3 生成器作为默认迭代器

  1. class Foo{
  2. constructor(){
  3. this.values=[1,2,3];
  4. }
  5. *[Symbol.iterator](){
  6. yield*this.values;
  7. }
  8. }
  9. const f=new Foo();
  10. for(let x of f){
  11. console.log(x); //返回 1 2 3
  12. }

第七章看了个寂寞,没弄懂迭代器和生成器所用的地方