《JavaScript高程》第七章
7.1理解迭代
计数就是最简单的迭代
for(let i=0;i<10;i++){
console.log(i);
}
1、迭代之前要事先知道如何使用数据结构
2、遍历顺序不是数据结构固有的,也就是说通过索引来遍历数组不是固有的
7.2迭代器模式
可迭代对象是一种抽象的说法,基本上可以把可迭代对象理解为数组 Array 和集合 set 这样的数据类型
let arr=[1,3,5,7,9];
let stt=new Set().add(1).add)(5).add(7).add(9);
for(let item of arr){
console.log(arr); //返回 1 3 5 7 9
}
for(let item of stt){
console.log(item); //返回 1 5 7 9
}
可迭代对象不一定是集合对象,也可能是类似数组结构的可循环对象 例如 string :
let str="String";
for(let s of str){
console.log(s); //返回 "S","t","i","n","g"
}
7.2.1可迭代协议Iterable
包括1、字符串 2、数组 3、映射 4、集合 5、arguments对象 6、NodeList等DOM集合
可迭代对象的原生语言特性包括 **for...of循环、数组解构、扩展操作符、Array.from()、创建集合、创建映射、Promise.all()、Promise.race()、yield ***
for...of循环
let str="string";
for(let s of str){
console.log(s); //返回 's','t','r','i','n','g';
}
数组解构
例如,解构String
sample1解构字符串
let str="String";
let [a,b,c,d,e,f]=str;
console.log(a); //返回 ‘S’
console.log(b); //返回 ‘t’
console.log(c); //返回 ‘r’
...
sample2解构数组
let arr=[1,3,5];
let [A,B,C]=arr;
console.log(A); //返回 1
console.log(B); //返回 3
console.log(C); //返回 5
sample映射map
let mp=new Map();
mp.set(1,123);
mp.set(2,234);
let vals=mp.values;
for(let item of vals){
console.log(item); //返回
}
set集合
let st=new Set();
st.add(1);
st.add(2);
st.add(3);
let ent=st.entries(); //这里利用entries函数获取迭代对象
for(let item of ent){
console.log(item) //这里返回entries方法返回的是数组[value,value];
}
arguments对象
let func=function(val,cur,sum){
let [a,b,c]=func.arguments;
console.log(a);
console.log(b);
console.log(c);
return a+b+c;
}
func(1,2,3); //输出 1 2 3 返回 1 + 2 + 3
7.3.1生成器
1、生成器的函数声明
只要在函数前面加个*号就可以定义一个生成器
function *func(a,b){
console.log(a);
return a+b;
}
let f=func();
console.log(f.next); //这里返回 ƒ next() { [native code] }
7.3.2 yield关键字,主要用于后台中
yield 关键字用来暂停和恢复一个生成器函数((function* 或遗留的生成器函数)。 yield相当于return,但不完全是return,弹出函数内部定义的值,遍历一遍之后就无法遍历了
function *func(){
let saleList=[1,3,5,7,9];
for(let i=0;i<saleList.length;i++){
yield saleList[i]
}
}
let f1=func();
console.log(f1.next().value); //返回 1
console.log(f1.next().value);// 返回 {value: 3, done: false}
for(let item of f1){
console.log(item); //返回 5 7 9
}
console.log(f1.next()); //返回 {value: undefined, done: true}
#### 用yield写递归算法
function *func(n){
if(n>0){
yield*func(n-1)
yield(n-1)
}
}
for(let x of func(4)){
console.log(x); //返回 0 1 2 3 4
}
7.3.3 生成器作为默认迭代器
class Foo{
constructor(){
this.values=[1,2,3];
}
*[Symbol.iterator](){
yield*this.values;
}
}
const f=new Foo();
for(let x of f){
console.log(x); //返回 1 2 3
}
第七章看了个寂寞,没弄懂迭代器和生成器所用的地方