TypeScript for ...与索引/键? [英] TypeScript for ... of with index / key?

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

问题描述

正如这里所介绍的,TypeScript引入了一个foreach循环:

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

但是没有索引/键?我希望如下所示:
$ b $ pre $ for(var item,someArray的key){...}

code>


解决方案

.forEach 已经具备这种能力:

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

但是如果你想要 c $ c>,那么你可以 <$ c

$ p $ for(const(); $ c $> map
数组到项和索引: someArray.map((item,index)=>({item,index}))){
console.log(item); // 9,2,5
console.log(index); // 0,1,2
}

这有点长,把它放在一个可重用的函数中:

$ p $ function toItemIndexes< T>(a:T []){
return a .map((item,index)=>({item,index}));

$ b $ for(toItemIndexes(someArray)的const {item,index}){
// .. etc ..
}

可更新版本

如果使用 - downlevelIteration 编译器选项进行编译,则将其作为目标ES3或ES5。

 <$ c (item:T [] | IterableIterator< T>){
let index = 0;
(项目的常量项目){
yield {item,index};
index ++;
}
}


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 already has this ability:

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

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

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

That's a little long, so it helps to throw it in a reusable function:

function toItemIndexes<T>(a: T[]) {
    return a.map((item, index) => ({ item, index }));
}

for (const {item, index} of toItemIndexes(someArray)) {
    // ..etc..
}

Iterable Version

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

function* toItemIndexes<T>(items: T[] | IterableIterator<T>) {
    let index = 0;
    for (const item of items) {
        yield { item, index };
        index++;
    }
}

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

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