Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();        
}
like image 627
user8570495 Avatar asked Oct 04 '17 16:10

user8570495


People also ask

Is there a forEach in TypeScript?

forEach() is an inbuilt TypeScript function which is used to calls a function for each element in the array. Parameter: This method accepts two parameter as mentioned above and described below: callback : This parameter is the Function to test for each element.

What does forEach return TypeScript?

forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

What is forEach in angular?

The angular. forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object.

What is for of loop in TypeScript?

The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object.


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.

like image 200
Julian Avatar answered Oct 14 '22 04:10

Julian