EN
TypeScript - create array
0 points
This article will show you how to create an array in TypeScript.
Quick solution:
xxxxxxxxxx
1
const arrayName: elementType[] = [element1, element2, element3, elementN];
xxxxxxxxxx
1
const myArray: string[] = ['Tom', 'Kate', 'Mary'];
2
3
console.log(myArray);
Output:
xxxxxxxxxx
1
[ 'Tom', 'Kate', 'Mary' ]
The above creation of an array can also be written as follows:
xxxxxxxxxx
1
const myArray: string[] = ['Tom', 'Kate', 'Mary'];
2
3
console.log(myArray);
Output:
xxxxxxxxxx
1
[ 'Tom', 'Kate', 'Mary' ]
or:
xxxxxxxxxx
1
const myArray: string[] = [];
2
3
myArray[0] = 'Tom';
4
myArray[1] = 'Kate';
5
myArray[2] = 'Mary';
6
// null on 3rd and 4th positions
7
myArray[5] = 'John';
8
9
console.log(myArray);
Output:
xxxxxxxxxx
1
[ 'Tom', 'Kate', 'Mary', <2 empty items>, 'John' ]
Note: this approach will cause automatic array resizing on assigning new indexes - by assigning non consecutive indexes, the array will be filled in unused areas with
null
values.
or:
xxxxxxxxxx
1
const myArray: string[] = Array(3);
2
3
myArray[0] = 'Tom';
4
myArray[1] = 'Kate';
5
myArray[2] = 'Mary';
6
7
console.log(myArray);
Output:
xxxxxxxxxx
1
[ 'Tom', 'Kate', 'Mary' ]
Note: this approach allocates necessary array space during array creation - not necessary resize in memory later.
or:
xxxxxxxxxx
1
const myArray: string[] = new Array('Tom', 'Kate', 'Mary');
2
3
console.log(myArray);
Output:
xxxxxxxxxx
1
[ 'Tom', 'Kate', 'Mary' ]
Note: the constructor-based approach used a much less frequent approach.