ES6-Generator基础用法
Generator简介: 生成器,本身是函数,执行后返回迭代对象,函数内部要配合yield使用Generator函数会分段执行,遇到yield暂停。 使用Generator注意点:function 和函数名之间需要带 * function* text(){ } Generator的yield注意点:yield是ES6新关键字,作用是使Generator(生成器)函数暂停。 function* text(){ yield 'a'; yield 'b'; yield 'c'; return 'd'; } let iterationObj = text(); console.log(iterationObj.next());//{value: "a", done: false} console.log(iterationObj.next());//{value: "b", done: false} console.log(iterationObj.next());//{value: "c", done: false} console.log(iterationObj.next());//{value: "d", done: true} yield后,必须return最后一个值,如果不return最后一个值value为undefined。 当每次执行后返回{value, done