For loop in TypeScript

By Apr 16, 2018

Description:

Here we explain how to use the for loops in TypeScript. There are several variations of the for loops and give some examples of use.

Preferencesoft

A for loop is a compound statement that allows you to repeat a statement or sequence of instructions several times.

Basic for loop

In its most common form, the for statement uses a variable that plays the counter role. This variable is initialized to a certain value, compared to an end value, and if this condition is checked then the loop statements are executed and then the variable is automatically incremented (or decremented).

Such a loop executes a specified number of times the instructions in the block.

FlowChart
for (initialization_statement; test_expression; update_statement) {
 // statements 
 }

We have programmed TypeScript examples into an ASP.NET application and all are run from the Index.cshtml file. This file is almost empty since we add objects directly from the TypeScript code. You can obviously replace the cshtml file with an html file.

Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<h1>For loops in TypeScript</h1>

Here is an example of a simple loop using a counter, which calculates and displays the factorial of a number and then displays the sequence of numbers from 1 to 10 in descending order.

LoopSimple.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopSimple {
    n: number;
    constructor(num : number) {
        this.n = num;
    }
    Go() {
        let html: string = '<div id="loop">\n';
        let fact = 1;
        for (let j = 2; j <= this.n; j++) {
            fact *= j;
        }
        html += this.n + "! = " + fact.toString() + "<br />\n";
        for (let i = this.n; i > 0; i--) {
            html += "   " + i.toString();
        }
        html += "\n</div>";
        $(document.body).append(html);
    }
}

$(document).ready(function () {
    let loop: LoopSimple = new LoopSimple(10);
    loop.Go();
});

Output

10! = 3628800
10 9 8 7 6 5 4 3 2 1

Let’s now give an example that generates an HTML list of items. This list is then inserted into the current page.

LoopList.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopList {
    n: number;
    constructor(num : number) {
        this.n = num;
    }
    List() {
        let html: string = '<div id="listing">\n<ul>';
        for (let i = 0; i < this.n; i++) {
            html += "<li>item "+i+"</li>\n";
        }
        html += "</ul>\n";
        html += "</div>\n";
        $(document.body).append(html); 
    }
}

$(document).ready(function () {
    let loop: LoopList = new LoopList(10);
    loop.List();
});

Output

  • item 0
  • item 1
  • item 2
  • item 3
  • item 4
  • item 5
  • item 6
  • item 7
  • item 8
  • item 9

In the following example, we generate an HTML list consisting of all the characters in a given character string.

LoopListC.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopListC {
    n: number;
    constructor(num : number) {
        this.n = num;
    }

    ListC(s : string) {
        let html: string = '<div id="listing">\n<ul>';
        let len = s.length;
        for (let i = 0; i < len; i++) {
            html += "<li>item " + s[i] + "</li>";
        }
        html += "</ul>\n</div>";
        $(document.body).append(html);
    }
}

$(document).ready(function () {
    let loop: LoopListChar = new LoopListChar(10);
    loop.ListC("ABCDEF");
});

Output

  • item A
  • item B
  • item C
  • item D
  • item E
  • item F

For optimization reasons, we calculate the length of the character string before the loop, avoiding to recalculate it each time in the condition: i < str.length. Thus, the length of the string is assigned to the variable len and the variable i is compared to len in the condition.

Nested for Loops

It is possible to put inside a for loop statement, other for loops.

For example, this can be used to easily traverse a two-dimensional array.

We will use nested loops to generate a table.

LoopTable.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopTable {
    n: number;
    constructor(num : number) {
        this.n = num;
    }

    Table(rows: number) {
        let html: string = '<div id="table">';
        html += "<table cellpadding=\"0\" cellspacing=\"0\"><tr>";
        for (let i = 1; i < 9; i++) {
            html += "<tr>";
            for (let j = 1; j < 5; j++) {
                html += "<td>[" + i + "," + j + "]</td>";
            }
            html += "</tr>";
        }
        html += "</tr>\n</div>";
        $(document.body).append(html);
    }

}

$(document).ready(function () {
    let loop: LoopTable = new LoopTable(10);
    loop.Table(10);
});

Output

[1,1][1,2][1,3][1,4]
[2,1][2,2][2,3][2,4]
[3,1][3,2][3,3][3,4]
[4,1][4,2][4,3][4,4]
[5,1][5,2][5,3][5,4]
[6,1][6,2][6,3][6,4]
[7,1][7,2][7,3][7,4]
[8,1][8,2][8,3][8,4]

Loop for general

In the most general form of the for-loop statement, wa can initialize multiple variables, place several statements executed at the end of the loop.

Let's give an example:

LoopCoordinates.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopCoordinates {
    n: number;
    constructor(num : number) {
        this.n = num;
    }

    Coordinates() {
        let html: string = '<div id="Coordinates">';
        for (let i = 5, j = 20; i < 9 && j > 5; i++ , j--) {
            html += "[" + i + "," + j + "]";
        }
        html += "</div>";
        $(document.body).append(html);
    }
}

$(document).ready(function () {
    let loop: LoopCoordinates = new LoopCoordinates(10);
    loop.Coordinates();
});

Output

[5,20][6,19][7,18][8,17]

In this example, we place all the characters of a string in a list, removing the first character of the string at each iteration. We use a for loop without initialization or update.

LoopListChar.ts

///<reference path="typings/jquery/jquery.d.ts" />
class LoopListChar {
    n: number;
    constructor(num : number) {
        this.n = num;
    }

    ListChar(s : string) {
        let html: string = '<div id="listing">\n<ul>';
        let str: string = s;
        for ( ; 0 < str.length; ) {
            html += "<li>item " + str[0] + "</li>";
            str = str.substr(1);
        }
        html += "</ul>\n</div>";
        $(document.body).append(html);
    }
}

$(document).ready(function () {
    let loop: LoopListChar = new LoopListChar(10);
    loop.ListChar("ABCDEF");
});

Output

  • item A
  • item B
  • item C
  • item D
  • item E
  • item F

TypeScript

Categories

Share

Follow


KodFor Privacy Policy