Arrays in ActionScript

Our first program will illustrate how to work with arrays. Here’s the full TypeScript source code for creating and manipulating arrays.

function main() {
    // Create an array `a` that will hold exactly 5 numbers.
    let a: number[] = new Array(5);
    console.log("emp:", a);

    // Set a value at an index using array[index] = value syntax.
    a[4] = 100;
    console.log("set:", a);
    console.log("get:", a[4]);

    // The builtin length property returns the length of an array.
    console.log("len:", a.length);

    // Declare and initialize an array in one line.
    let b: number[] = [1, 2, 3, 4, 5];
    console.log("dcl:", b);

    // You can also have the compiler count the number of elements for you.
    let c: number[] = Array.from([1, 2, 3, 4, 5]);
    console.log("dcl:", c);

    // If you specify the index with `,` the elements in
    // between will be zeroed.
    let d: number[] = Array.apply(null, new Array(5)); d[0] = 100; d[3] = 400; d[4] = 500;
    console.log("idx:", d);

    // Array types are one-dimensional, but you can
    // compose types to build multi-dimensional data structures.
    let twoD: number[][] = Array(2).fill(0).map(() => Array(3).fill(0));
    for (let i = 0; i < 2; i++) {
        for (let j = 0; j < 3; j++) {
            twoD[i][j] = i + j;
        }
    }
    console.log("2d:", twoD);

    // Create and initialize multi-dimensional arrays at once
    let threeD: number[][] = [
        [1, 2, 3],
        [1, 2, 3]
    ];
    console.log("2d:", threeD);
}

main();

When you run the code, you will get the following output:

$ ts-node arrays.ts
emp: [ <5 empty items> ]
set: [ <4 empty items>, 100 ]
get: 100
len: 5
dcl: [ 1, 2, 3, 4, 5 ]
dcl: [ 1, 2, 3, 4, 5 ]
idx: [ 100, <2 empty items>, 400, 500 ]
2d: [ [ 0, 1, 2 ], [ 1, 2, 3 ] ]
2d: [ [ 1, 2, 3 ], [ 1, 2, 3 ] ]

Arrays in TypeScript are lists of elements defined between square brackets and can be manipulated using a variety of methods. Arrays in TypeScript can be empty initially, and their elements can be set or fetched using the index notation. You can also initialize arrays with values, and TypeScript provides various ways to create multi-dimensional arrays.