For Loop in TypeScript

For Loop in TypeScript

A for loop is classified as an iteration statement. The for loop is used when you know in advance how many times the script should run. To code a for statement, you code the keyword "for" followed by three statements in parentheses and a block of code in braces. The statements are separated by semicolons. The first statement in parentheses initializes the counter. The second statement is a conditional expression that causes the block of code to be executed as long as it's true. The third statement modifies the counter. It's executed after the block of code in the for loop is executed.

Syntax

for ( initialize a counter; conditional statement; increment a counter)

{
  do this code;
 }

The following example shows the multiplication table of 5. In this example I have a table class and define a loop in the class which starts with n=1. The loop will continue to run as long as n is less than 10. n will increase by 1 each time the loop runs. Let's use the following.

Step 1

Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is shown as:


starting-window-type-script.gif

Give the name of your application as "table" and then click ok.

Step 2

After this session the project has been created; your new project should look like this. This window is called the Solution Explorer. The Solution Explorer contains the ts file, js file, CSS file and HTML file:

table-explorer-type-script.gif

Coding

super.ts

class table

{

    x: number;

    constructor(x:number, )

    {   

        for (var n = 1; n <= 10; n++)

        {         

            var y = x * n;

            var span = document.createElement("span"); 

             span.innerText = x+"*"+n+"=" + y+"\n"

             document.body.appendChild(span); 

        } 

    }

}

var p = new table(5);

 

superkeyworddemo.html

<!DOCTYPEhtml>

<htmllang="en"xmlns="http://www.w3.org/1999/xhtml">

<head>

    <metacharset="utf-8"/>

    <title>Example Of Multiplication Table of 5</title>

    <linkrel="stylesheet"href="app.css"type="text/css"/> 

</head>

<body>

    <h1>Multiplication Table of 5</h1>

    <divstyle="color:#0094ff"id="content">

        <scriptsrc="app.js">

        </script>

    </div>

</body>

</html>

 

app.js

var table = (function ()

{

    function table(x)

    {

        for (var n = 1; n <= 10; n++)

        {

            var y = x * n;

            var span = document.createElement("span");

            span.innerText = x + "*" + n + "=" + y + "\n";

            document.body.appendChild(span);

        }

    }

    return table;

})();

var p = new table(5);

 

Output


 final-result-table-type-script.gif

Reference By

http://www.typescriptlang.org/

Up Next
    Ebook Download
    View all

    Test

    Read by 16 people
    Download Now!
    Learn
    View all