EN
TypeScript - for loop / foreach loop
3 points
In TypeScript there are few ways to use for
loop.
xxxxxxxxxx
1
let text = 'Text...';
2
3
for(let i = 0; i < text.length; ++i)
4
console.log(text[i]);
Output:
xxxxxxxxxx
1
T
2
e
3
x
4
t
5
.
6
.
7
.
xxxxxxxxxx
1
let array = [ 1, 2, 3, 'text' ];
2
3
for(let entry of array)
4
console.log(entry);
Output:
xxxxxxxxxx
1
1
2
2
3
3
4
text
xxxxxxxxxx
1
let object = {
2
'key1' : {
3
name : 'John',
4
age : 43
5
},
6
'key2' : {
7
name : 'Kate',
8
age : 54
9
},
10
'key3' : {
11
name : 'Diego',
12
age : 21
13
},
14
};
15
16
for(let key in object) {
17
let entry = object[key];
18
19
console.log(key + ' : ' + entry.name + ', ' + entry.age);
20
}
Output:
xxxxxxxxxx
1
key3 : Diego, 21
2
key1 : John, 43
3
key2 : Kate, 54
Note:
for...in
loop only iterates over enumerable and non-Symbol properties.