Iterator
//Iterator Example
function nameIterator(names) {
let nextIndex = 0;
return {
next:function(){
return nextIndex<names.length ?
{value:names[nextIndex++],done:false} :
{done:true};
}
}
}
//Create an array of names
const namesArray = ['Jack','Jill','John'];
//Init iterator and pass in the names array
const names = nameIterator(namesArray);
console.log(names)
console.log(names.next());
console.log(names.next());
console.log(names.next());
console.log(names.next());
console.log(names.next());
Generator
//Generator Example
function* sayNames(){ // * generator
yield `Jack`;
yield `Jill`;
yield `John`;
}
const name = sayNames();
console.log(name.next());
console.log(name.next());
console.log(name.next());
console.log(name.next());
返回相同
Generator用作ID生成器
//ID Creator
function* craeteids(){
let index=0;
while(true){
yield index++;
}
}
const gen = craeteids();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);