function *gen() {}
function *gen() { console.log(1); yield 'generator1'; // 通过 yield 定义一个状态 console.log(2); yield 'generator2'; // 又定义一个状态 }
// 1 it.next(); // { value: 'generator1', done: false }
function *gen() { console.log(1); const val1 = yield 'generator1'; // 调用可迭代对象的 next()函数时传递的参数放入 val1 中 console.log(val1) console.log(2); const val2 = yield 'generator2'; // 再次调用可迭代对象的 next()函数时传递的参数放入 val2 中 console.log(val2); } let it = gen(); // 调用Generator函数生成一个可迭代对象 it.next(); // 不能传递参数 it.next('one'); // 将 one 赋值给 val1 it.next('two'); // 将 two 赋值给 val2
let obj = { name: 'zhangsan', age: 66, [Symbol.iterator]: function *() { let keys = Object.keys(this); for (let i = 0; i < keys.length; i++) { yield this[keys[i]]; } } } let it = obj[Symbol.iterator](); it.next(); // { value: 'zhangsan', done: false } it.next(); // { value: 66, done: false } it.next(); // { value: undefined, done: true }