![]() |
VOOZH | about |
An array is a data structure that stores a fixed-size collection of elements of the same type in contiguous memory locations. Elements are accessed by index, starting from 0. Arrays can store multiple values, but cannot expand once their size is declared.
Features of an Array
TypeScript supports arrays similar to JavaScript. There are two ways to declare an array:
Arrays can be declared using square brackets [] with a type annotation:
Syntax:
let array_name[:datatype] = [val1, val2, valn..]
Example:
TypeScript array can contain elements of different data types, as shown below.
Syntax:
let array_name: Array = [val1, val2, valn..] Example: Multi Type Array
Example: Access Array Elements
There are two types of an array
It is the simplest form of an array that contains only one row for storing data. It contains single set of the square bracket ("[]").
Syntax:
let array_name[:datatype]; Initialization:
array_name = [val1, val2, valn..]Example:
Output:
Array[0]: 1
Array[1]: 2The data is stored in rows and columns (also known as matrix form) in a Multi-dimensional array.
Syntax:
let arr_name:datatype[][] = [ [a1, a2, a3], [b1, b2, b3] ]; Initialization:
let arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1, val2, val 3], [v1, v2, v3]]; Example:
Output:
10
20
30
50
60
70We can create an Array by using or initializing the Array Object. The Array constructor is used to pass the following arguments to create an Array:
Syntax:
let arr_name:datatype[] = new Array(values); Example:
Output:
GEEKSFORGEEKS
2200
Java
AbhishekWe can pass an Array to a function by specifying the Array name without an index.
Example:
Output
GEEKSFORGEEKS
2300
Java
Abhishek The spread operator can be used to initialize arrays and objects from another array or object. It can also be used for object destructuring. It is a part of ECMAScript 6 version.
Example:
Output:
CopiedArray: 1, 2, 3
NewArray: 1, 2, 3, 7, 8
MergedArray: 1, 2, 3, 4, 5, 6