本文介绍了如何循环来自发生器的JavaScript迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我们假设我们有以下生成器: var gen = function *(){ for(var i = 0; i< 10; i ++){ yield i; } }; 循环遍历迭代器最有效的方法是什么? 目前,如果完成属性设置为 true ,则手动检查: var item ,iterator = gen(); while(item = iterator.next(),!item.done){ console.log(item.value); } 解决方案 iterable(一个支持@@ iterator的对象)是使用 for..of ,像这样 'use strict'; function * gen(){ for(var i = 0; i< 10; i ++){ yield i; } } for(let value of gen()){ console.log(value); } 或者,如果你想要一个数组,那么你可以使用 Array.from ,像这样 console.log(Array.from(gen()); // [0,1,2,3,4,5,6,7,8,9] Let's assume that we have following generator:var gen = function* () { for (var i = 0; i < 10; i++ ) { yield i; }};What is the most efficient way to loop through the iterator ?Currently I do it with checking manually if done property is set to true or not:var item , iterator = gen();while (item = iterator.next(), !item.done) { console.log( item.value );} 解决方案 The best way to iterate any iterable (an object which supports @@iterator), is to use for..of, like this'use strict';function * gen() { for (var i = 0; i < 10; i++) { yield i; }}for (let value of gen()) { console.log(value);}Or, if you want an Array out of it, then you can use Array.from, like thisconsole.log(Array.from(gen());// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 这篇关于如何循环来自发生器的JavaScript迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-02 07:15