Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript:可迭代对象的两个必要条件 #31

Open
smileyby opened this issue May 25, 2021 · 0 comments
Open

JavaScript:可迭代对象的两个必要条件 #31

smileyby opened this issue May 25, 2021 · 0 comments
Labels

Comments

@smileyby
Copy link
Owner

拥有 Symbol.iterator 方法 objSymbol.iterator 的结果被称为 迭代器(iterator)。由它处理进一步的迭代过程。
一个迭代器必须有 next 方法,它返回 {done: Boolean, value: any} 对象,done: true 表示迭代结束,否则value就是下一个值
Javascript 内置的可迭代对象:字符串和数组

let range = {
from: 1,
to: 5,

Symbol.iterator {
this.current = this.from;
return this;
},

next() {
if (this.current <= this.to) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};

for (let num of range) {
alert(num); // 1, 然后是 2, 3, 4, 5
}

@smileyby smileyby added the JavaScript ☀️ JavaScript label May 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant