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
  1. for (variablename in object)  
  2. {  
  3.   statement or block to execute  
  4. }  
The following example prints out the properties of a Web browser's document object by using a 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 a "for-in loop" 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 contains the ts file, js file, CSS file, and HTML files.
 

Coding

 
forinloop.ts
  1. class forin {  
  2.  navigatefunction() {  
  3.   var aProperty: string;  
  4.   document.writeln("Navigate Object Properties<br><br>");  
  5.   for (aProperty in navigator) {  
  6.    document.write(aProperty);  
  7.    document.write("<br />");  
  8.   }  
  9.  }  
  10. }  
  11. window.onload = () => {  
  12.  var show = new forin();  
  13.  show.navigatefunction();  
  14. };  
forinloopdemo.html
  1. <!DOCTYPEhtml>  
  2. <htmllang="en"  
  3.     xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <metacharset="utf-8"/>  
  6.         <title>for-in example</title>  
  7.         <linkrel="stylesheet"href="app.css"type="text/css"/>  
  8.         <scriptsrc="app.js">  
  9.         </script>  
  10.     </head>  
  11.     <body>  
  12.         <h2>For-in loop example in TypeScript HTML App</h2>  
  13.         <h3style="color:red">Document Object Properties  
  14.         </h3>  
  15.         <divid="content"/>  
  16.     </body>  
  17. </html>  
app.js
  1. var forin = (function() {  
  2.  function forin() {}  
  3.  forin.prototype.navigatefunction = function() {  
  4.   var aProperty;  
  5.   for (aProperty in document) {  
  6.    document.write(aProperty);  
  7.    document.write("<br />");  
  8.   }  
  9.  };  
  10.  return forin;  
  11. })();  
  12. window.onload = function() {  
  13.  var show = new forin();  
  14.  show.navigatefunction();  
  15. };  
Output
 
result-for-in-loop.jpg
 
Referenced By
http://www.typescriptlang.org/


Similar Articles