2016-08-13 15 views
0

はここjsfiddleに取り組んでいる私のデモです:予想される識別子、文字列または数値* [Symbol.iterator]

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でそれを書き換える:

0123:
class Animal { 
    *[Symbol.iterator]() { 

    } 
} 

私は、このエラーメッセージが出ていだから、

1

、私の質問:それを修正するにはどのように?

答えて

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) 
 
}

しかし、それはあなたが物事を行うことになっているか、実際にはありません。 this.animals.values function`ではありません: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) 
 
}

+0

'キャッチされない例外TypeErrorを必要とするだけのものが提供されます解決する必要があります –

関連する問題