You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何用Lambda表达式替换双重循环简化代码?

Simplifying Your Marker Filter Code with Arrow Functions

Sure thing! You can replace those nested for loops with a much cleaner approach using Array.filter() and Array.includes()—leveraging arrow functions (lambdas) exactly as you wanted. Here's the refactored code:

this.markersDisplay = this.markersSource; // Start with all markers
if (this.isValid(this.selectedMarkersType)) {
  // Filter markers where MarkerType is in the selected list
  this.markersDisplay = this.markersSource.filter(marker => 
    this.selectedMarkersType.includes(marker.MarkerType)
  );
}

How this compares to your original code:

  • filter() iterates over each marker in markersSource and keeps only the ones that pass our condition, replacing your outer loop entirely.
  • includes() checks if the current marker's MarkerType exists in selectedMarkersType—this handles the inner loop and the break logic (since includes() stops searching as soon as it finds a match).
  • The core logic is identical to your original code, but it’s far more concise and easier to read at a glance.

This follows modern TypeScript/JavaScript best practices and cuts out all the loop boilerplate. It’s a standard pattern for filtering items based on membership in another array.

内容的提问来源于stack exchange,提问作者Nemanja Andric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:12:29