简体   繁体   English

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

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

I really like using the foreach construct for "for loops" in C#.我真的很喜欢在 C# 中为“for 循环”使用foreach构造。 I think it's very clean, efficient and readable.我认为它非常干净、高效和可读。

Is there a similar construct in TypeScript? 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();        
}

Yes, the for ... of是的, for ... of

Eg例如

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

Because you're using TypeScript, this also works in IE.因为您使用的是 TypeScript,所以这也适用于 IE。 See https://basarat.gitbooks.io/typescript/content/docs/for...of.html :请参阅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.对于 ES6 之前的目标,TypeScript 将为 (var i = 0; i < list.length; i++) 类型的循环生成标准。

In plain Javascript, so without Typescript, this isn't supported in IE ( source )在纯 Javascript 中,因此没有 Typescript,IE 不支持此功能(

Update: for scoping is let more similar to C# than var .更新:为作用域是let更多的类似于C#比var Updated the example.更新了示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM