代码之家  ›  专栏  ›  技术社区  ›  EGxo

优化目标代码

  •  0
  • EGxo  · 技术社区  · 8 年前

    我的对象有27个部分,前两个是独立的,其余的都是一样的。我相信它可以通过循环进行优化,但我不知道如何实现这一点,如果有人能提供帮助,我将不胜感激。

    代码如下:

    var BingoData = {Username: username, cardnumber: serial, Cell1: tablecells[0].innerHTML, Cell2: tablecells[1].innerHTML, Cell3: tablecells[2].innerHTML, Cell4: tablecells[3].innerHTML, Cell5: tablecells[4].innerHTML};
    
    2 回复  |  直到 8 年前
        1
  •  4
  •   Chris Riebschlager    8 年前

    你可以 Cells 数组并用 for

    var BingoData = {Username: username, cardnumber: serial, Cells: []};
    
    for(let i = 0; i < tablecells.length; i++) {
        BingoData.Cells.push(tablecells[i].innerHTML);
    }
    
        2
  •  2
  •   Jonas Wilms    8 年前

    1) 以大写字母开头的标识符仅适用于构造函数

    2) 可以对单元格使用数组

    3) 您可以映射 tablecells 到其innerHTML属性

     const bingo = {
       username,
       cardnumber: serial,
       cells: tablecells.map(cell => cell.innerHTML)
    };