JS iterator
程序员文章站
2024-02-20 20:20:23
...
JS Iterator
Create Custom Iterator next : () =>
function iterator(){
let step = 0;
return {
next : ()=>{
step ++;
if (step ==1 ){
return {value : 'cake', done : false};
}
if (step ==2 ){
return {value : 'yogurt', done : false};
}
if (step == 3) {
return {value : 'bread', done : false};
}
else{
return {value : undefined, done :true}
}
}
};
}
const it = iterator();
console.log(it); // { next: [Function: next] }
console.log(it.next()); // {value : 'cake', done : false};
console.log(it.next()); // {value : 'yogurt', done : false};
console.log(it.next()); // {value : 'bread', done : false};
console.log(it.next()); // {value : undefined, done :true}
The same result for next(){} below
function iterator(){
let step = 0;
return {
next() {
step ++;
if (step ==1 ){
return {value : 'cake', done : false};
}
if (step ==2 ){
return {value : 'yogurt', done : false};
}
if (step == 3) {
return {value : 'bread', done : false};
}
else{
return {value : undefined, done :true}
}
}
};
}
- Output
[email protected] MINGW64 ~
$ node iterator-test.js
{ next: [Function: next] }
{ value: 'cake', done: false }
{ value: 'yogurt', done: false }
{ value: 'bread', done: false }
{ value: undefined, done: true }
Spread operator …iterator
function iterator(){
let step = 0;
return {
next : ()=>{
step ++;
if (step ==1 ){
return {value : 'cake', done : false};
}
if (step ==2 ){
return {value : 'yogurt', done : false};
}
if (step == 3) {
return {value : 'bread', done : false};
}
else{
return {value : undefined, done :true}
}
}
};
}
const my_it = {}
my_it[Symbol.iterator] = iterator;
console.log(...my_it); // cake yogurt bread
with this
function iterator(){
let step = 0;
return {
prefix : "delicious",
next() {
step ++;
if (step ==1 ){
return {value : this.prefix + ' cake' , done : false};
}
if (step ==2 ){
return {value : this.prefix + ' yogurt', done : false};
}
if (step == 3) {
return {value : this.prefix + ' bread', done : false};
}
else{
return {value : undefined, done :true}
}
}
};
}
const it = iterator();
console.log(it); // { prefix: 'delicious', next: [Function: next] }
console.log(it.next()); //{ value: 'delicious cake', done: false }
console.log(it.next()); // { value: 'delicious yogurt', done: false }
console.log(it.next()); // { value: 'delicious bread', done: false }
console.log(it.next()); // { value: undefined, done: true }
下一篇: JS之迭代器 Iterator