-
Notifications
You must be signed in to change notification settings - Fork 0
JavaScript迭代协议 #10
Copy link
Copy link
Open
Labels
Description
// this is like __iter__ method in python
class MyIter {
constructor(limit) {
this.now = 0
this.limit = limit
this[Symbol.iterator] = () => ({
next: () => {
if (this.now < this.limit) {
this.now += 1
return { value: this.now**2, done: false }
} else {
return { done: true }
}
}
})
}
}
let mi = new MyIter(5)
[...mi] // [1, 4, 9, 16, 25]
// Then again
[...mi] // []
let nmi = new MyIter(3)
for (let i of nmi) {
console.log(i)
}
// 1
// 4
// 9OR LIKE THIS
class MyIter {
constructor(limit) {
this.now = 0
this.limit = limit
}
[Symbol.iterator]() {
return {
next: () => {
if (this.now < this.limit) {
this.now += 1
return { value: this.now ** 2, done: false }
} else {
return { done: true }
}
}
}
}
}Reactions are currently unavailable