尝试通过调用(let x of xy)使用Iterator类会产生“ SyntaxError:let是保留的标识符”

时间:2019-02-01 20:36:24

标签: javascript

如果我想知道我的迭代器类有任何问题。预先感谢您的帮助。

class Group {
  constructor(arr = []){
    this.array = arr;
  }
  add(number) {
    this.array.push(number);
  }
  delete(number){
    this.array = this.array.filter(n => n != number);
  }
  has(number){
    return this.array.includes(number);
  }  
  static from(array){
    return new this(array);
  }
}

class GroupIterator{
    constrctor(group){
        this.x = 0;
        this.group = group;
    }
  next() {
    if (this.x == this.group.array.length) return {done: true};
    var val = this.x
    this.x++;
    return {val, done: false};
}

问题在于以下调用。

for(let value of Group.from(["a", "b", "c"])) {
  console.log(value);
}
// → a
// → b
// → c

先谢谢您

1 个答案:

答案 0 :(得分:4)

由于您要调用Group.from来创建Group,因此需要Group拥有一个允许迭代的生成器,否则会得到一个错误,提示它不是可迭代的。添加

*[Symbol.iterator]() {
  for (const item of this.array) {
    yield item;
  }
}

作为Group(而非GroupIterator)的方法:

class Group {
  constructor(arr = []){
    this.array = arr;
  }
  *[Symbol.iterator]() {
    for (const item of this.array) {
      yield item;
    }
  }
  add(number) {
    this.array.push(number);
  }
  delete(number){
    this.array = this.array.filter(n => n != number);
  }
  has(number){
    return this.array.includes(number);
  }  
  static from(array){
    return new this(array);
  }
}
for(let value of Group.from(["a", "b", "c"])) {
  console.log(value);
}
// → a
// → b
// → c

另一个避免双for..of包装的选择是调用并返回 array Symbol.iterator

[Symbol.iterator]() {
  return this.array[Symbol.iterator]();
}

class Group {
  constructor(arr = []){
    this.array = arr;
  }
  [Symbol.iterator]() {
    return this.array[Symbol.iterator]();
  }
  add(number) {
    this.array.push(number);
  }
  delete(number){
    this.array = this.array.filter(n => n != number);
  }
  has(number){
    return this.array.includes(number);
  }  
  static from(array){
    return new this(array);
  }
}
for(let value of Group.from(["a", "b", "c"])) {
  console.log(value);
}
// → a
// → b
// → c