You need to enable JavaScript to run this app. JavaScript数组操作:将class为col的对象移入前序含fieldGroup的对象
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript数组操作:将class为col的对象移入前序含fieldGroup的对象

报错原因

你代码报错的核心问题是遍历过程中修改原数组导致索引偏移:
forEach的遍历索引是按照遍历开始时的数组长度生成的,你用splice删除元素后,数组长度变短,后续元素的索引都会自动减1,但forEach不会感知到这个变化,仍然会按原索引顺序遍历。这就导致后续匹配到的col对象,它的前一个位置(index-1)的元素可能根本不携带fieldGroup属性,访问fieldGroup返回undefined,调用push自然就抛出错误。

修复方案

这里提供两种可直接运行的实现:

方案1:倒序遍历(原地修改原数组)

倒序遍历不会出现索引偏移问题,因为删除靠后的元素不会影响还未遍历的前半部分索引:

for (let index = arr.length - 1; index >= 0; index--) {
  const item = arr[index];
  if (item.class === "col") {
    // 向前查找最近的带fieldGroup的元素
    let prevIdx = index - 1;
    while (prevIdx >= 0 && !arr[prevIdx].hasOwnProperty('fieldGroup')) prevIdx--;
    if (prevIdx >= 0) {
      arr[prevIdx].fieldGroup.push(item);
      arr.splice(index, 1);
    }
  }
}

方案2:构建新数组(不修改原数组,逻辑更直观)

直接遍历原数组构建结果,完全规避索引问题,性能也更优:

const res: typeof arr = [];
let currentGroup: typeof arr[0]['fieldGroup'] | null = null;

for (const item of arr) {
  if (item.class === 'col') {
    currentGroup?.push(item);
    continue;
  }
  res.push(item);
  if ('fieldGroup' in item) currentGroup = item.fieldGroup;
}

// 如需覆盖原数组可执行:arr = res;

两种方案执行后都能得到你给出的预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:57:02