TypeScript for ... of with index/key? [英] TypeScript for ... of with index / key?

查看:16
本文介绍了TypeScript for ... of with index/key?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As described here TypeScript introduces a foreach loop:

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

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

But isn't there any index/key? I would expect something like:

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

推荐答案

.forEach 已经有这个能力:

.forEach already has this ability:

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

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

But if you want the abilities of for...of, then you can map the array to the index and value:

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

可迭代版本

如果您使用 --downlevelIteration 编译器选项编译,这将适用于 ES3 或 ES5.

This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration compiler option.

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 的回答中所述.

If you are able to target ES6+ environments then you can use the .entries() method as outlined in Arnavion's answer.

这篇关于TypeScript for ... of with index/key?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆