Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-in statement

Tags:

typescript

TypeScript docs say nothing about loop like for or for-in. From playing with the language it seems that only any or string variables are supported in for loop.

Why has this decision been made?

Why not use the type information and have strongly-typed iteration variable?

like image 359
Ido Ran Avatar asked Oct 18 '12 08:10

Ido Ran


People also ask

What are the differences between for of and for in statements?

Difference for..in and for..of : Both for..in and for..of are looping constructs which are used to iterate over data structures. The only difference between them is the entities they iterate over: for..in iterates over all enumerable property keys of an object. for..of iterates over the values of an iterable object.

What is the correct syntax for for in loop?

The for...in statements combo iterates (loops) over the properties of an object. The code block inside the loop is executed once for each property.

Can I use for in loop?

Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.

How does a for loop start?

The initialization statement is executed before the loop begins. The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.


2 Answers

In Typescript 1.5 and later, you can use for..of as opposed to for..in

var numbers = [1, 2, 3];  for (var number of numbers) {     console.log(number); } 
like image 54
brianbruff Avatar answered Sep 19 '22 07:09

brianbruff


TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {}; obj['0'] = 'quote zero quote'; obj[0.0] = 'zero point zero'; obj['[object Object]'] = 'literal string "[object Object]"'; obj[<any>obj] = 'this obj' obj[<any>undefined] = 'undefined'; obj[<any>"undefined"] = 'the literal string "undefined"';  for(var key in obj) {     console.log('Type: ' + typeof key);     console.log(key + ' => ' + obj[key]); } 

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string 0 => zero point zero Type: string [object Object] => this obj;  Type: string undefined => the literal string "undefined"  
like image 39
Ryan Cavanaugh Avatar answered Sep 17 '22 07:09

Ryan Cavanaugh