TypeScript for ... of with index / key?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36108110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript for ... of with index / key?
提问by Mick
回答by David Sherret
.forEach
already has this ability:
.forEach
已经有这个能力:
const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
});
But if you want the abilities of for...of
, then you can map
the array to the index and value:
但是如果你想要 的能力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
}
That's a little long, so it may help to put it in a reusable function:
这有点长,所以把它放在一个可重用的函数中可能会有所帮助:
function toEntries<T>(a: T[]) {
return a.map((value, index) => [index, value] as const);
}
for (const [index, value] of toEntries(someArray)) {
// ..etc..
}
Iterable Version
可迭代版本
This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration
compiler option.
如果您使用--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+
Array.prototype.entries() - ES6+
If you are able to target ES6+ environments then you can use the .entries()
method as outlined in Arnavion's answer.
如果您能够针对 ES6+ 环境,那么您可以使用Arnavion 的回答中.entries()
概述的方法。
回答by Arnavion
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
for (var [key, item] of someArray.entries()) { ... }
In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babelto make the output work on ES5 runtimes.
在 TS 中,这需要针对 ES2015,因为它需要运行时支持迭代器,而 ES5 运行时则不支持。你当然可以使用Babel 之类的东西来使输出在 ES5 运行时上工作。
回答by Sylvain
"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)
“老派javascript”来拯救(对于那些不熟悉/不喜欢函数式编程的人)
for (let i = 0; i < someArray.length ; i++) {
let item = someArray[i];
}
回答by Karanvir Kang
回答by Galdor
Or another old school solution:
或者另一个老派的解决方案:
var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
console.log(item); // 9,2,5
i++;
}