概述
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
inakamono@ninja 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 iteratorJS Iterator的全部内容,希望文章能够帮你解决JS iteratorJS Iterator所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复