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 inmarkersSourceand keeps only the ones that pass our condition, replacing your outer loop entirely.includes()checks if the current marker'sMarkerTypeexists inselectedMarkersType—this handles the inner loop and thebreaklogic (sinceincludes()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
相关产品推荐
相关产品推荐

