EN
TypeScript - foreach with index
8 points
In TypeScript it is possible to create foreach with index in following ways.
xxxxxxxxxx
1
let array : Array<string> = ['a', 'b', 'c'];
2
3
array.forEach((item: string, index: number): void => {
4
console.log(`${index} : ${item}`);
5
});
Output:
0 : a
1 : b
2 : c
Run it online here.
xxxxxxxxxx
1
let array : Array<string> = ['a', 'b', 'c'];
2
let index = 0;
3
4
for(let entry of array) {
5
console.log(`${index++} : ${entry}`);
6
}
Output:
0 : a
1 : b
2 : c
Run it online here.
xxxxxxxxxx
1
class Entry<T> {
2
public constructor(public index: number, public item: T) {
3
// nothing here...
4
}
5
}
6
7
function mapArray<T>(array: Array<T>): Array<Entry<T>> {
8
let result = array.map((item: T, index: number): Entry<T> => {
9
return new Entry<T>(index, item);
10
});
11
12
return result;
13
}
Example:
xxxxxxxxxx
1
let array : Array<string> = ['a', 'b', 'c'];
2
3
for(let {index, item} of mapArray(array)) {
4
console.log(`${index} : ${item}`);
5
}
Output:
0 : a
1 : b
2 : c
Run it online here.
xxxxxxxxxx
1
class Entry<T> {
2
public constructor(public index: number, public item: T) {
3
// nothing here...
4
}
5
}
6
7
function* mapArray<T>(array: Array<T>): IterableIterator<Entry<T>> {
8
for(let i = 0; i < array.length; ++i)
9
yield new Entry(i, array[i]);
10
}
Example:
xxxxxxxxxx
1
let array : Array<string> = ['a', 'b', 'c'];
2
3
for(let {index, item} of mapArray(array)) {
4
console.log(`${index} : ${item}`);
5
}
Compiling and running:
xxxxxxxxxx
1
$ tsc -t ES6 Script.ts
2
$ node Script.js
Output:
0 : a
1 : b
2 : c
Run it online here.
Note: for
yield
keyword support--downlevelIteration
parameter during compilation is necessary.