用于索引/键的...的TypeScript?

Mic*_*ick 118 foreach for-loop typescript

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

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

但是没有任何索引/密钥吗?我希望有类似的东西:

for (var item, key of someArray) { ... }
Run Code Online (Sandbox Code Playgroud)

Dav*_*ret 227

.forEach 已经具备这种能力:

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

但是如果你想要的能力for...of,那么你可以map将数组转换为项目和索引:

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

这有点长,所以它有助于将其放入可重用的功能:

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

for (const {item, index} of toItemIndexes(someArray)) {
    // ..etc..
}
Run Code Online (Sandbox Code Playgroud)

可转换版本

如果使用编译--downlevelIteration器选项进行编译,则在针对ES3或ES5时将起作用.

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

  • 你怎么能休息一下; 在那个forEach? (3认同)
  • @Mick它取决于目标.当转换到ES6时,它不会这样做.转换时额外代码的原因只是为了让ES6代码在以前的版本中运行. (2认同)

Arn*_*ion 28

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries

for (var [key, item] of someArray.entries()) { ... }
Run Code Online (Sandbox Code Playgroud)

在TS中,这需要针对ES2015,因为它需要运行时支持迭代器,而ES5运行时则不需要.您当然可以使用像Babel这样的东西来使输出在ES5运行时上运行.


Syl*_*ain 26

"老派javascript"拯救(对于那些不熟悉/喜欢功能性编程的人)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}
Run Code Online (Sandbox Code Playgroud)

  • 我实际上最喜欢这个答案。不使用额外的方法来为每个元素生成索引。 (2认同)

Kar*_*ang 14

在处理集合时,可以使用for..in TypeScript运算符来访问索引.

var test = [7,8,9];
for (var i in test) {
   console.log(i + ': ' + test[i]);
} 
Run Code Online (Sandbox Code Playgroud)

输出:

 0: 7
 1: 8
 2: 9
Run Code Online (Sandbox Code Playgroud)

见演示

  • 请注意,“i”是一个字符串,而不是带有 for..in 循环的 int。使用“i”执行算术运算将导致字符串连接。例如,当 i = 0 时,(i + 1) 将等于“01” (4认同)

Gal*_*dor 8

或者另一个老派的解决方案:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}
Run Code Online (Sandbox Code Playgroud)