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();
}
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.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
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.
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With