16

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();        
}
Julian
  • 33,915
  • 22
  • 119
  • 174
user8570495
  • 1,645
  • 5
  • 19
  • 29

1 Answers1

20

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.

Julian
  • 33,915
  • 22
  • 119
  • 174
  • 2
    Do note that `for .. of ..` can be used with JS [Iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol), while the pre-ES6 translation will _not_ work with those. – This company is turning evil. Oct 04 '17 at 19:26
  • 2
    @Kroltan also worth noting that the compiler has a `downlevelIteration` option that enables support even in ES3 environments. – Gerrit0 Oct 05 '17 at 04:38