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

如何将JavaScript中的嵌套for循环改写为单行代码?

消除嵌套for循环的最佳方式

你的原代码:

for (const house of this.houses){
  for (const room of house.rooms){
    this.plans.push(room.layout.id);
  }
}

最简洁高效的方式是用flatMap,一行就能搞定需求:

方案1:直接生成新数组(覆盖原plans)

this.plans = this.houses.flatMap(house => house.rooms.map(room => room.layout.id));

方案2:追加到现有plans数组

如果不想覆盖原数组,要把新的布局ID追加进去,用扩展运算符配合flatMap即可:

this.plans.push(...this.houses.flatMap(house => house.rooms.map(room => room.layout.id)));

原理说明

flatMap会先对每个house执行map操作,把单栋房屋的所有房间布局ID转换成一个子数组,随后自动将所有子数组扁平成一维数组,完美替代嵌套循环的逻辑,代码更简洁可读性也更强。

兼容旧环境的替代方案

如果你的运行环境不支持flatMap(比如旧版浏览器),可以用map加flat的组合写法:

this.plans.push(...this.houses.map(house => house.rooms.map(room => room.layout.id)).flat());

或者用reduce实现,不过代码稍显繁琐:

this.plans = this.houses.reduce((acc, house) => {
  acc.push(...house.rooms.map(room => room.layout.id));
  return acc;
}, []);

优先推荐flatMap方案,它是JS专门为这类嵌套数组提取场景设计的API,写法最直观高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:45:00