关于javascript:请问如何简化下面的代码

35次阅读

共计 1108 个字符,预计需要花费 3 分钟才能阅读完成。

性能形容

当 const mergeTable=[2] 时,
函数返回
{rowSpan: 2}
{rowSpan: 0}

当 const mergeTable=[2,3] 时, 函数返回
{rowSpan: 2}
{rowSpan: 0}
{rowSpan: 3}
{rowSpan: 0}
{rowSpan: 0}

当 const mergeTable=[2,3,3,2] 函数返回
{rowSpan: 2}
{rowSpan: 0}
{rowSpan: 3}
{rowSpan: 0}
{rowSpan: 0}
{rowSpan: 3}
{rowSpan: 0}
{rowSpan: 0}
{rowSpan: 2}
{rowSpan: 0}

须要优化的函数

性能曾经实现,代码冗余,请问如何优化

// const mergeTable=[2] // 测试 ok
const mergeTable = [2, 3]; // 测试 ok
// const mergeTable=[2,3,3,2]; // 测试 ok

// 如何简化这个函数
function renderRowSpan(index) {for (let i in mergeTable) {i=Number(i);
    if (i === 0) {if (index === 0) {return { rowSpan: mergeTable[0] };
      } else if (index < mergeTable[0]) {return { rowSpan: 0};
      }
    }

    if (i === 1) {if (index === mergeTable[0]) {return { rowSpan: mergeTable[1] };
      }
      if (index < mergeTable[0] + mergeTable[1]) {return { rowSpan: 0};
      }
    }

    if (i === 2) {if (index === mergeTable[0] + mergeTable[1]) {return { rowSpan: mergeTable[2] };
      }
      if (index < mergeTable[0] + mergeTable[1] + mergeTable[2]) {return { rowSpan: 0};
      }
    }


      if (i === 3) {if (index === mergeTable[0] + mergeTable[1]+mergeTable[2]) {return { rowSpan: mergeTable[3] };
          }
          if (index < mergeTable[0] + mergeTable[1] + mergeTable[2]+ mergeTable[3]) {return { rowSpan: 0};
          }
      }
  }
}

// 内部办法会渲染 index
for (let index = 0; index < 10; index++) {console.log(renderRowSpan(index));
}

正文完
 0