let generator = function* () { //这里的*不加就会报错,这种声明方法就是generator函数
yield 1;
yield* [2,3,4]; //在数组前加* 遍历所有元素,不加* 直接遍历整体
yield 5;
yield {name:'123',num:123};
};
var iterator = generator(); //generator返回的是Iterator对象,所以调用时候要使用next()
console.log( iterator.next() )// { value: 1, done: false }
console.log( iterator.next() ) // { value: 2, done: false }
console.log( iterator.next() )// { value: 3, done: false }
console.log( iterator.next() )// { value: 4, done: false }
console.log( iterator.next() )// { value: 5, done: false }
console.log( iterator.next() )// { value: {name:'123',num:123}, done: false }
console.log( iterator.next() )// { value: undefined, done: true }
主要的作用就是遍历比较复杂的数据结果