首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在TypeScript中是否有类似于C#实现的foreach构造?

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

Stack Overflow用户
提问于 2017-10-05 00:17:25
回答 1查看 889关注 0票数 16

我真的很喜欢在C#中为"for循环“使用foreach构造。我认为它是非常干净,高效和可读性的。

在TypeScript中有类似的构造吗?例如,而不是这样:

代码语言:javascript
复制
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);
}

我想这样做:

代码语言:javascript
复制
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();        
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-05 00:18:43

是的,for ... of

例如。

代码语言:javascript
复制
for(let author of authors)
{ 
  ... 
}

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

For pre ES6 targets TypeScript将生成标准for (var i= 0;i< list.length;i++)类型的循环。

在纯Javascript中,没有Typescript,这在IE (source)中是不受支持的

更新:对于作用域来说,let更类似于C#,而不是var。更新了示例。

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46569617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档