EN
TypeScript - for loop / foreach loop
3
points
In TypeScript there are few ways to use for
loop.
1. Classic for
loop over string example
// ONLINE-RUNNER:browser;
let text = 'Text...';
for(let i = 0; i < text.length; ++i)
console.log(text[i]);
Output:
T
e
x
t
.
.
.
2. Foreach loop (for...of
loop) over array example
// ONLINE-RUNNER:browser;
let array = [ 1, 2, 3, 'text' ];
for(let entry of array)
console.log(entry);
Output:
1
2
3
text
3. for...in
loop over object example
// ONLINE-RUNNER:browser;
let object = {
'key1' : {
name : 'John',
age : 43
},
'key2' : {
name : 'Kate',
age : 54
},
'key3' : {
name : 'Diego',
age : 21
},
};
for(let key in object) {
let entry = object[key];
console.log(key + ' : ' + entry.name + ', ' + entry.age);
}
Output:
key3 : Diego, 21
key1 : John, 43
key2 : Kate, 54
Note:
for...in
loop only iterates over enumerable and non-Symbol properties.