【问题标题】:Expected identifier, string or number with *[Symbol.iterator]带有 *[Symbol.iterator] 的预期标识符、字符串或数字
【发布时间】:2016-08-13 18:00:04
【问题描述】:

这是我正在使用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]() {

    }
}

我收到此错误消息:

预期的标识符、字符串或数字

那么,我的问题是:如何解决它?

【问题讨论】:

    标签: javascript visual-studio iterator


    【解决方案1】:

    您不能使用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 中所做的那样,但您必须使用 delegation (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

    【讨论】:

    • Uncaught TypeError: this.animals.values is not a function
    猜你喜欢
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多