We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The text was updated successfully, but these errors were encountered:
ECMAScript 6 规范新增了两个高级特性“迭代器和生成器。能够清晰、高效、方便地实现迭代。
循环是迭代机制的基础。 迭代会在一个有序集合上进行。("有序"可以理解为集合中所有项都可以按照既定的顺序被遍历到,特别是开始和结束项有明确的定义。)数组是JavaScript中有序集合的最典型例子。
即可以把有些结构成为“可迭代对象”(iterable),因为它们实现了正式的Itetable接口,而且可以通过迭代器Iterator消费。 可以把可迭代对象理解成数组或集合这样的集合类型的对象。它们包含的元素都是有限的,而且都具有无歧义的遍历顺序。 可迭代对象不一定是集合对象,也可以是仅仅具有类似数组行为的其他数据结构。
// 可迭代对象 let arr = ['foo', 'bar']; // 迭代器工厂函数 console.log(arr[Symbol.iterator]); // f values() { [native code] } // 迭代器 let iter = arr[Symbol.iterator](); console.log(iter); // ArrayIterator {} // 执行迭代 console.log(iter.next()); // { done: false, value: 'foo' } console.log(iter.next()); // { done: false, value: 'bar' } console.log(iter.next()); // { done: true, value: undefined }
可选的 return()方法用于指定在迭代器提前关闭时执行的逻辑。执行迭代的结构在想让迭代器知道它不想遍历到可迭代对象耗尽时,就可以“关闭”迭代器。可能的情况包括:
拥有在一个函数快内暂停和恢复代码块执行的能力。比如,使用生成器可以自定义迭代器和实现协程。
生成器的形式是一个函数,函数名称前面加一个星号(*)表示它是一个生成器。只要是可以定义函数的地方,就可以定义生成器。 注意:箭头函数不能用来定义生成器函数。
调用生成器函数会产生一个生成器对象。生成器对象一开始处于暂停执行(suspended)的状态。与迭代器相似,生成器对象也实现了 Iterator 接口,因此具有 next()方法。调用这个方法会让生成器开始或恢复执行。
生成器的独特之处在于支持 yield 关键字,这个关键字能够暂停执行生成器函数。使用 yield 关键字还可以通过 next()方法接收输入和产生输出。在加上星号之后,yield 关键字可以将跟在它后面的可迭代对象序列化为一连串值。
Sorry, something went wrong.
No branches or pull requests
题目:js中的迭代器和生成器
The text was updated successfully, but these errors were encountered: