HappyCoding HappyCoding - 3 months ago 15
Javascript Question

Expected identifier, string or number with *[Symbol.iterator]

Here is my demo which is working on

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





But when I rewrite it in Visual Studio:

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

}
}


I'm getting this error message:


Expected identifier, string or number


1

So, my question: how to fix it?

Answer

You can't define a generator using the class syntax. This is a direct translation of your code into ES6 that actually functions.

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

But that's not really how you're supposed to do things. The Symbol.iterator only needs resolve an iterable valueArray.prototype.values will provide just the thing you need

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

Comments