2017-10-04 58 views
16

我真的很喜欢在C#中使用“for循环”的foreach构造。我认为它非常干净,高效和可读。类似于C#实现的TypeScript中是否存在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();   
} 

回答

20

是的,for ... of

例如

for(let author of authors) 
{ 
    ... 
} 

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

对于预靶向ES6打字稿将生成的标准(VAR I = 0;我< list.length;我++)类型的循环。

在普通的JavaScript,所以不打字原稿,这不是在IE(source)支持

更新:对于作用域是letvar更类似于C#。更新了示例。

+2

请注意''.. .. .. ..'可以与JS [Iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol)一起使用,而ES6之前的翻译将不会与这些工作一起工作。 – Kroltan

+2

@Kroltan还值得注意的是,编译器有一个'downlevelIteration'选项,即使在ES3环境中也支持。 – Gerrit0

相关问题