【问题标题】:Get item at position "x" on Iterable class在 Iterable 类的位置“x”处获取项目
【发布时间】:2017-11-24 16:20:05
【问题描述】:

我正在创建一个可迭代的类,它使用 for 循环,如下所示:

for(let i of myClassInstance) {
  console.log(i)
}

但是,如果我想在这样的索引处抓取一个项目,我会得到undefined

console.log(myClassInstance[2])

我能从课堂上获得物品吗?这是我班级的迭代器,我需要其他东西来完成这项工作吗?

class myClass {
  public [Symbol.iterator]() {
    let items = this._items
    let pointer = 0
    return {
      next(): IteratorResult<T> {
        if (pointer < items.length) {
          return { done: false, value: items[pointer++] }
        }
        return { done: true, value: items[items.length - 1] }
      }
    }
  }
}

【问题讨论】:

  • 为什么不添加一个方法item(index) 并使用它呢?不确定是否可以在 js 中创建索引属性
  • 我可以,我只是希望我可以那样做
  • 也许最接近的是Array.from?这就是 ES6
  • 考虑扩展数组。 class MyClass extends Array {...}

标签: javascript arrays typescript iterator


【解决方案1】:

我能从课堂上获得物品吗?

要使用数组索引,请转换为数组:

console.log(Array.from(myClassInstance)[2]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2019-11-13
    相关资源
    最近更新 更多