JavaScript 数组操作优化:使用 reduce() 和 forEach() 提升性能

这段代码使用 map() 方法进行数组遍历和数据处理,但可以进一步优化以提高代码效率。

原始代码:

data.map((item: any, index2: number) => {
  const len = item?.diVoList?.length;
  item.diVoList?.map((ite: any, index: number) => {
    arr = [
      ...arr,
      {
        serial: index2 + 1,
        projectType: item.projectType,
        projectId: item.projectId,
        projectName: item.projectName,
        targetDi: item.targetDi,
        actualDi: item.actualDi,
        spm: ite.spm,
        department: ite.department,
        targetDis: ite.targetDi,
        actualDis: ite.actualDi,
        span: index === 0 ? len : 0,
      },
    ];
    return arr;
  });
  return arr;
});
const tableData = arr.map((item1: any, index: number) => {
  item1.key = index;
  return item1;
});

优化方案:

  1. 使用 Array.reduce() 替换 map()reduce() 方法可以将数组中的元素累积到一个结果数组中,避免了 map() 方法中频繁创建新数组带来的性能损耗。
  2. 使用 forEach() 遍历内部数组forEach() 方法可以更简洁地遍历内部数组,并将元素添加到结果数组中。
  3. 使用 push() 添加元素push() 方法可以直接将元素添加到现有数组中,避免了 ...arr 语法带来的性能损耗。
  4. 简化代码结构: 避免嵌套过多的逻辑,使代码更易于阅读和理解。

优化后的代码:

const arr = data.reduce((result: any[], item: any, index2: number) => {
  const len = item?.diVoList?.length;
  item.diVoList?.forEach((ite: any, index: number) => {
    result.push({
      serial: index2 + 1,
      projectType: item.projectType,
      projectId: item.projectId,
      projectName: item.projectName,
      targetDi: item.targetDi,
      actualDi: item.actualDi,
      spm: ite.spm,
      department: ite.department,
      targetDis: ite.targetDi,
      actualDis: ite.actualDi,
      span: index === 0 ? len : 0,
    });
  });
  return result;
}, []);

const tableData = arr.map((item: any, index: number) => {
  return { ...item, key: index };
});

优化后的代码 使用 reduce()forEach() 方法,减少了循环次数和内存占用,提高了代码效率。同时,代码结构也更加简洁易懂。

注意: 这只是一个可能的优化方案,具体优化方案需要根据实际情况进行调整。

JavaScript 数组操作优化:使用 reduce() 和 forEach() 提升性能

原文地址: http://www.cveoy.top/t/topic/n0ml 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录