TypeScript for ... of with index / key?

新手上路,请多包涵

如此 处所述, TypeScript 引入了一个 foreach 循环:

 var someArray = [9, 2, 5];
for (var item of someArray) {
    console.log(item); // 9,2,5
}

但是没有任何索引/键吗?我希望是这样的:

 for (var item, key of someArray) { ... }

原文由 Mick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 576
1 个回答

.forEach 已经有这个能力:

 const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
});

但是如果你想要 for...of 的能力,那么你可以 map 数组的索引和值:

 for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
}

这有点长,所以把它放在一个可重用的函数中可能会有所帮助:

 function toEntries<T>(a: T[]) {
    return a.map((value, index) => [index, value] as const);
}

for (const [index, value] of toEntries(someArray)) {
    // ..etc..
}

可迭代版本

如果您使用 --downlevelIteration 编译器选项编译,这将在针对 ES3 或 ES5 时起作用。

 function* toEntries<T>(values: T[] | IterableIterator<T>) {
    let index = 0;
    for (const value of values) {
        yield [index, value] as const;
        index++;
    }
}

Array.prototype.entries() - ES6+

如果您能够针对 ES6+ 环境,那么您可以使用 .entries() 方法,如 Arnavion 的回答 中所述。

原文由 David Sherret 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进