簡體   English   中英

TypeScript 中是否有類似於 C# 實現的 foreach 構造?

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

我真的很喜歡在 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

對於 ES6 之前的目標,TypeScript 將為 (var i = 0; i < list.length; i++) 類型的循環生成標准。

在純 Javascript 中,因此沒有 Typescript,IE 不支持此功能(

更新:為作用域是let更多的類似於C#比var 更新了示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM