const obj2={ [Symbol.iterator](){ let i=-1 const txt=[ 'this will output in both case', 'just output in call `next` by hand' ] return { next(){ i++ return {done:i===txt.length-1,value:txt[} } } } } const obj1={ [Symbol.iterator]:function* (){ yield'this will output in both case' return'just output in call `next` by hand' } } console.log('obj1 output') var g=obj1[Symbol.iterator]() console.log(g.next().value) console.log(g.next().value) console.log('----') for(let i of obj1){ console.log(i) } console.log('obj2 output') var g=obj2[Symbol.iterator]() console.log(g.next().value) console.log(g.next().value) console.log('----') for(let i of obj2){ console.log(i) } // => 输出结果:
// obj1 output // this will output in both case // just output in call `next` by hand // ---- // this will output in both case
// obj2 output // this will output in both case // just output in call `next` by hand // ---- // this will output in both case