这是我在 jsfiddle
上运行的演示:
class Animal {
constructor(...names) {
this.animals = names
}
*[Symbol.iterator]() {
for (let animal of this.animals) {
yield animal
}
}
}
var animals = new Animal('cat', 'dog', 'tiger');
for (let animal of animals) {
console.log(animal)
}
但是当我在 Visual Studio 中重写它时:
class Animal {
*[Symbol.iterator]() {
}
}
我收到此错误消息:
Expected identifier, string or number
那么,我的问题:如何解决它?
最佳答案
您无法使用 class
语法定义生成器。这是将您的代码直接转换为实际运行的 ES6。
class Animal {
constructor(...names) {
this.animals = names
}
}
// you could define the generator on the prototype here ...
// but make sure you read the second half of this answer
Animal.prototype[Symbol.iterator] = function* () {
for (let animal of this.animals) {
yield animal
}
}
var animals = new Animal('cat', 'dog', 'tiger');
for (let animal of animals) {
console.log(animal)
}
// cat
// dog
// tiger
但这并不是你真正应该做的事情。 Symbol.iterator
只需要解析一个可迭代值 — Array.prototype.values将提供您所需要的东西
class Animal {
constructor(...names) {
this.animals = names
}
[Symbol.iterator]() {
return this.animals.values()
}
}
var animals = new Animal('cat', 'dog', 'tiger');
for (let animal of animals) {
console.log(animal)
}
// cat
// dog
// tiger
您可以将迭代器定义为生成器,就像您在OP中所做的那样,但您必须使用委托(delegate) (yield*
)获得您想要的行为 -
class Animal {
constructor(...names) {
this.animals = names
}
*[Symbol.iterator]() {
yield* this.animals
}
}
var animals = new Animal('cat', 'dog', 'tiger');
for (let animal of animals) {
console.log(animal)
}
// cat
// dog
// tiger
关于javascript - 预期的标识符、字符串或数字,带 *[Symbol.iterator],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935515/