For-In Statement With Object In TypeScript

For-in statement with objects in TypeScript

You can use a for-in statement to loop through the properties of an object. A for-in statement loops through all the defined properties of an object that are enumerable. Each time through the loop, it saves the next property name in the loop variable.

Most built-in properties aren't enumerable, but the properties you add to an object are always enumerable. You can't change whether or not a property is enumerable.

You can use the property IsEnumerable method of the Object object to determine whether a property is enumerable.

Syntax

for (variablename in object)

{

  statement or block to execute

}

The following example prints out the properties of a Web browser's document object by using for-in loop. Let's use the following steps.

Step 1

Open Visual Studio 2012 and click "File" -> "New" -> "Project..". A window is opened. Give the name of your application as "forinloop" and then click ok.

Step 2

After this session the project has been created. A new window is opened on the right side. This window is called the Solution Explorer. Solution Explorer is contains the ts file, js file, css file and html files.

Coding

forinloop.ts

class forin

    navigatefunction()

    {

        var aProperty: string;

        document.writeln("Navigate Object Properties<br><br>");

        for (aProperty in navigator)

        {           

            document.write(aProperty);

            document.write("<br />");

        }

    }

}

window.onload = () =>

{

    var show = new forin();

    show.navigatefunction();

};

 

forinloopdemo.html

<!DOCTYPEhtml>

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

<head>

    <metacharset="utf-8"/>

    <title>for-in example</title>

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

    <scriptsrc="app.js"></script>

</head>

<body>

    <h2>For-in loop example in TypeScript HTML App</h2>

    <h3style="color:red">Document Object Properties</h3>

    <divid="content"/>

</body>

</html>

 

app.js

var forin = (function ()

{

    function forin() { }

    forin.prototype.navigatefunction = function ()

    {

        var aProperty;

        for (aProperty in document)

        {

            document.write(aProperty);

            document.write("<br />");

        }

    };

    return forin;

})();

window.onload = function ()

{

    var show = new forin();

    show.navigatefunction();

};

 

Output


result-for-in-loop.jpg

 

Reference By

http://www.typescriptlang.org/

Up Next
    Ebook Download
    View all

    Test

    Read by 16 people
    Download Now!
    Learn
    View all