for…of
有迭代器Iterator接口的有序结构都可以通过for…of来进行遍历
const str = "know"; for (let k of str) { console.log(k); // k n o w } const arr = [1, 2]; for (let k of arr) { console.log(k); // 1 2 } const set = new Set("abc"); for (let k of set) { console.log(k); // a b c } const map = new Map().set("name", "tom").set("age", 15); for (let k of map) { console.log(k); // [ 'name', 'tom' ] [ 'age', 15 ] }
解构、扩展运算符、Array.from
有迭代器Iterator接口的有序结构都可以使用上面的解构、扩展运算符、Array.from;有序结构作为参数,会调用默认的 Iterator 接口
const arr = [1, 2]; const [n1, n2] = arr; console.log(n1, n2); // 1 2 const str = "tom"; const [a, b, c] = str; console.log(a, b, c); // t o m const set = new Set().add(1).add("w").add(5); const [s1, s2] = set; console.log(s1, s2); // 1 w const map = new Map().set("name", "tom").set("age", 15); const newArr = [...map]; console.log(newArr); // [ [ 'name', 'tom' ], [ 'age', 15 ] ] const res = Array.from('hello'); console.log(res) // [ 'h', 'e', 'l', 'l', 'o' ]
Promise.all和Promise.race
Promise.all和Promise.race的参数不仅可以是数组,还可以是其他的有迭代器接口的有序结构
基本使用
生成器函数执行会生成一个迭代器
function* getResult() { yield 1; yield 2; yield 3; } const iterator = getResult(); for (let k of iterator) { console.log(k); }
yield * 语法
yield * 后面跟具有迭代器接口的有序结构
function* getResult() { yield* [1, 2, 3, 4]; yield* "abc"; } const iterator = getResult(); for (let k of iterator) { console.log(k); }
yield * 自定义迭代器
class GenIterator { constructor(data) { this.data = data; } *[Symbol.iterator]() { yield* this.data; } } const iterator = new GenIterator("7890"); for (let k of iterator) { console.log(k); // 7 8 9 0 }
yield遍历DOM
function* traverse(elementList) { for (let ele of elementList) { yield ele; if (ele.children) { yield* traverse(ele.children); } } } const container = document.getElementById("container"); for (let node of traverse([container])) { console.log(node); }