我非常喜欢在 C# 中为“for 循环”使用 foreach
结构。我认为它非常干净、高效且可读。
TypeScript 中是否有类似的结构?例如,而不是这个:
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);
}
我想这样做:
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();
}
最佳答案
是的,for ... of
例如
for(let author of authors)
{
...
}
因为您使用的是 TypeScript,所以这在 IE 中也适用。 参见 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.
在普通的 Javascript 中,如果没有 Typescript,这在 IE 中不受支持(source)
更新:对于作用域,let
比 var
更类似于 C#。更新了示例。
关于c# - TypeScript 中是否有类似于 C# 实现的 foreach 构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46569617/