Reputation: 8913
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) { ... }
Upvotes: 277
Views: 507727
Reputation: 3968
See: Array.prototype.entries()
for (const [index, 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.
Upvotes: 98
Reputation: 106640
.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
});
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..
}
Iterable Version
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+
If you are able to target ES6+ environments then you can use the .entries()
method as outlined in Arnavion's answer.
Upvotes: 475
Reputation: 1955
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++;
}
Upvotes: 12
Reputation: 1579
"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];
}
Upvotes: 71
Reputation: 2239
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
Upvotes: 21