详解简单易懂的 ES6 Iterators 指南和示例(2)

const array = ['a', 'b', 'c', 'd', 'e']; const iterator = array[Symbol.iterator](); const first = iterator.next().value iterator.next().value // Since it was skipped, so it's not assigned const third = iterator.next().value iterator.next().value // Since it was skipped, so it's not assigned const last = iterator.next().value

扩展操作符(…)

const array = ['a', 'b', 'c', 'd', 'e']; const newArray = [1, ...array, 2, 3];

等价于:

const array = ['a', 'b', 'c', 'd', 'e']; const iterator = array[Symbol.iterator](); const newArray = [1]; for (let nextValue = iterator.next(); nextValue.done !== true; nextValue = iterator.next()) { newArray.push(nextValue.value); } newArray.push(2) newArray.push(3)

Promise.all 和 Promise.race 接受可迭代对象

Maps 和 Sets

让 myFavouriteAuthors 可迭代

下面是一个实现,它使myFavouriteAuthors 具有可迭代性:

const myFavouriteAuthors = { allAuthors: { fiction: [ 'Agatha Christie', 'J. K. Rowling', 'Dr. Seuss' ], scienceFiction: [ 'Neal Stephenson', 'Arthur Clarke', 'Isaac Asimov', 'Robert Heinlein' ], fantasy: [ 'J. R. R. Tolkien', 'J. K. Rowling', 'Terry Pratchett' ], }, [Symbol.iterator]() { // 获取数组中的所有作者 const genres = Object.values(this.allAuthors); // 存储当前类型和索引 let currentAuthorIndex = 0; let currentGenreIndex = 0; return { // Implementation of next() next() { // 根据当前的索引获取对应的作者信息 const authors = genres[currentGenreIndex]; // 当遍历完数组 authors是,oNotHaveMoreAuthors 为 true const doNothaveMoreAuthors = !(currentAuthorIndex < authors.length); if (doNothaveMoreAuthors) { // 加一继续访问下一个 currentGenreIndex++; // 重置 currentAuthorIndex = 0; } // 如果所有 genres 都遍历完了结,那么我们需要告诉迭代器不能提供更多的值。 const doNotHaveMoreGenres = !(currentGenreIndex < genres.length); if (doNotHaveMoreGenres) { return { value: undefined, done: true }; } // 如果一切正常,从当genre 返回 作者和当前作者索引,以便下次,下一个作者可以返回。 return { value: genres[currentGenreIndex][currentAuthorIndex++], done: false } } }; } }; for (const author of myFavouriteAuthors) { console.log(author); } console.log(...myFavouriteAuthors)

通过本文获得的知识,你可以很容易地理解迭代器是如何工作的,这种逻辑可能有点难以理解。因此,理解这个概念的最佳方法是多多敲死代码,多多验证!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/62e79158db1352948345863381cfe567.html