TypeScript中是否有类似于C#实现的foreach构造?

use*_*495 16 c# typescript angular

我真的很喜欢foreach在C#中使用"for循环" 的构造.我认为它非常干净,高效且易读.

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);
}
Run Code Online (Sandbox Code Playgroud)

我想这样做:

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();        
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ian 20

是的 for ... of

例如

for(let author of authors)
{ 
  ... 
}
Run Code Online (Sandbox Code Playgroud)

因为您使用的是TypeScript,所以这也适用于IE.请参阅https://basarat.gitbooks.io/typescript/content/docs/for...of.html:

对于ES6之前的目标,TypeScript将为(var i = 0; i <list.length; i ++)类型的循环生成标准.

在普通的Javascript中,所以没有Typescript,IE(源代码)不支持

更新:对于范围界定let更类似于C#而不是var.更新了示例.

  • 请注意`for .. of ..`可以与JS [Iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol)一起使用,而pre -ES6翻译将不会与那些人合作. (2认同)
  • @Kroltan还值得注意的是,编译器有一个`downlevelIteration`选项,即使在ES3环境中也能支持. (2认同)