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

JS如何在遇到list元素时将组件数组拆分为多个独立数组

实现代码

你之前的实现问题是没有做分片触发逻辑,所有符合条件的非list元素都被存入了同一个数组,没有按list做拆分。可以参考如下实现:

const components = [
  { name: 'heading'  },
  { name: 'paragraph' },
  { name: 'hr' },
  { name: 'heading' },
  { name: 'list' },
  { name: 'hr' },
  { name: 'paragraph' },
  { name: 'list' }
];

const result = [] // 存储最终拆分后的多个数组
const currentGroup = [] // 临时收集当前批次的非list元素
const list = [] // 保留原有收集list元素的逻辑

components.forEach((component, index) => {
  switch (component.name) {
    case 'heading':
    case 'hr':
    case 'paragraph':
      currentGroup.push(component)
      break
    case 'list':
      // 碰到list就完成一次拆分,非空的当前批次存入结果
      if (currentGroup.length) {
        result.push([...currentGroup])
        currentGroup.length = 0
      }
      list.push(`${component.name}-${index}`)
      break
  }
})

// 收尾:遍历结束后剩余的未拆分元素也要存入结果
if (currentGroup.length) {
  result.push([...currentGroup])
}

console.log(result)

运行后result的输出完全匹配你的期望:

[
  [
    { name: 'heading'  },
    { name: 'paragraph' },
    { name: 'hr' },
    { name: 'heading' }
  ],
  [
    { name: 'hr' },
    { name: 'paragraph' }
  ]
]

内容的提问来源于stack exchange,提问作者x-ray

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:51:02