Is there a foreach construct in TypeScript similar to the C# implementation?

Viewed 918

I really like using the foreach construct for "for loops" in C#. I think it's very clean, efficient and readable.

Is there a similar construct in TypeScript? For example, instead of this:

setAuthorFilters(selectedAuthors)
{
    selectedAuthors.forEach(x => this.setAuthorFilter(x));
    this.updateUrl();        
}

setAuthorFilter(selectedAuthor)
{
    this.vm.SelectAuthors = this.vm.SelectAuthors.filter(x => x.id !== selectedAuthor.id);
    this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice();
    this.vm.CurrentSelectedAuthors.push(selectedAuthor);
}

I'd like to do this:

setAuthorFilters(selectedAuthors)
{
    foreach(var selectedAuthor in selectedAuthors)
    {
        this.vm.SelectAuthors = this.vm.SelectAuthors.filter(x => x.id !== selectedAuthor.id);
        this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice();
        this.vm.CurrentSelectedAuthors.push(selectedAuthor);
    }
    this.updateUrl();        
}
1 Answers

Yes, the for ... of

E.g.

for(let author of authors)
{ 
  ... 
}

Because you're using TypeScript, this also works in IE. See https://basarat.gitbooks.io/typescript/content/docs/for...of.html :

For pre ES6 targets TypeScript will generate the standard for (var i = 0; i < list.length; i++) kind of loop.

In plain Javascript, so without Typescript, this isn't supported in IE (source)

Update: for scoping is let more similar to C# than var. Updated the example.

Related