Tôi thực sự thích sử dụng cấu trúc foreach
cho "cho vòng" trong C#. Tôi nghĩ nó rất sạch sẽ, hiệu quả và dễ đọc.Có cấu trúc foreach trong TypeScript tương tự như triển khai C# không?
Có cấu trúc tương tự trong TypeScript không? Ví dụ, thay vì điều này:
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);
}
Tôi muốn làm điều này:
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();
}
Lưu ý rằng 'cho .. của ..' có thể được sử dụng với JS [Iterables] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol), trong khi bản dịch trước ES6 sẽ _không hoạt động với các bản dịch đó. – Kroltan
@Kroltan cũng đáng chú ý là trình biên dịch có tùy chọn 'downlevelIteration' cho phép hỗ trợ ngay cả trong môi trường ES3. – Gerrit0