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) { ... }
This question is related to
for-loop
foreach
typescript
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++;
}
"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)
for (let i = 0; i < someArray.length ; i++) {
let item = someArray[i];
}
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 Babel to make the output work on ES5 runtimes.
You can use the for..in TypeScript operator to access the index when dealing with collections.
var test = [7,8,9];
for (var i in test) {
console.log(i + ': ' + test[i]);
}
Output:
0: 7
1: 8
2: 9
See Demo
Source: Stackoverflow.com