如何在JavaScript中计算表列?

如何在JavaScript中计算表列?,javascript,angularjs,json,html-table,Javascript,Angularjs,Json,Html Table,使用JavaScript,我返回一个商店服务员列表,并在最后一行(服务员)后动态插入一行,在total列下显示所有服务员的总数。但是现在我需要做的是在running total列中显示每个服务员的运行总数 这是我要展示的,很明显,跑步总数公式不在这里 我知道有一种更具角度感的方法。我肯定会以这种方式实施。但现在,我想让你们关注我要走的路,关于计算总柱数。以下是我希望大家特别关注的内容: var total = 0; document.querySelectorAll("td:nth-chi

使用JavaScript,我返回一个商店服务员列表,并在最后一行(服务员)后动态插入一行,在total列下显示所有服务员的总数。但是现在我需要做的是在running total列中显示每个服务员的运行总数

这是我要展示的,很明显,跑步总数公式不在这里

我知道有一种更具角度感的方法。我肯定会以这种方式实施。但现在,我想让你们关注我要走的路,关于计算总柱数。以下是我希望大家特别关注的内容:

var total = 0;
  document.querySelectorAll("td:nth-child(4)").forEach((cell, index) => {
    this.attendantNames.forEach(a=>{
      this.total += a.total;
    });
    cell.innerText = this.total;
  });
但是,如果您需要查看整个控制器代码,它就在这里:

export default class StoreTotalsController {
  constructor() {
    this.attendantNames = [];
    this.stores = [];
    this.emptyResult = true;
    this.totals = 0;
    this.total = 0;
    this.cellValue = "";
    this.runningTotalCells;
    //this.previousTotal = 0;
  }

  getAttendants() {
    showLoader('Searching');
    const baseUrl = '/src/areas/store-totals/services/tender-total-data.json';
    const getStores = new Request(baseUrl, {
      method: 'GET'
      });
    fetch(getStores).then(function(response){
      return response.json();
    }).then(resp => {
    if (!(resp[0] && resp[0].error)) {
      this.attendantNames = resp.stores[0].attendants;
      this.attendantNames.forEach(a=>{
        this.totals += a.total;
        console.log("Attendant :" , a.attendantName, "Had a total of :" , a.total, "With running total " , this.totals);
      });

      //Row at bottom displaying total of totals
      var table = document.querySelector('.table');
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
      var td3 = document.createElement('td');
      var tr = document.createElement("tr");
      tr.setAttribute("class", "last-row");
      var td1Data = document.createTextNode('  ');
      var td2Data = document.createTextNode('Total');
      var td3Data = document.createTextNode('$' + this.totals.toFixed(2));
      td1.appendChild(td1Data);
      td2.appendChild(td2Data);
      td3.appendChild(td3Data);
      tr.appendChild(td1);
      tr.appendChild(td2);
      tr.appendChild(td3);
      table.appendChild(tr);

      this.emptyResult = false;
      this.errorMessage = null;

    } else {
      this.errorMessage = resp[0].error.name;
    }
    digest();

  var total = 0;
  document.querySelectorAll("td:nth-child(4)").forEach((cell, index) => {
    this.attendantNames.forEach(a=>{
      this.total += a.total;
    });
    cell.innerText = this.total;
  });
    showLoader(false);
    });
  }

  searchIfReady() {
    if (this.search && this.date && this.date.isValid()) {
      this.getSearch();
    }
  }

  updateDate(date) {
    this.date = moment(date).startOf('day');
    this.searchIfReady();
  }
}
StoreTotalsController.$inject = ['$stateParams'];

您可以使用
$(“td:nth child(2)”)循环第二个单元格。每个
然后将该单元格值添加到total变量中,并使用
$(this)将总计打印到下一个td。next('td')。text(total)

var总计=0;
$(“td:n个子项(2)”)。每个子项(函数(索引){
total=parseInt($(this).text())+parseInt(total);
$(this).next('td').text(总计);
});
表格{
文本对齐:居中;
}
运输署{
宽度:100px;
背景颜色:橙色;
}
th{
背景颜色:橙色;
}

名称
全部的
运行总数
埃里克
100
拉尔斯
20
帕特里克
200
代码笔:

  • 您需要注意删除
    $
    符号
  • 在parseInt之后,由于数字的格式,您将得到(根据您的示例)2、8和5,而不是2000、8000和5000。 我天真地把它乘以1000。应该找到更好的解决方案,这只是一个草图
  • 您需要将数字格式化回您想要的格式 解决方案就在那里,我把细节留给你:)

    对于您的代码,它应该是这样的:

    this.attendantNames.forEach((attendant, index) => {
        const table = document.querySelector('.table');
        const attendantRow = table.querySelectorAll('tr')[index];
        const runningTotalCell = attendantRow.querySelectorAll('td')[2];
    
        //am assuming that this.totals is 0 at the beginning of this loop, right?
        this.totals += parseInt(attendant.total); //am not sure of format attendant.total have in your data, not sure if you need parsing here and if  it will work
    
        runningTotalCell.innerHTML = `$${this.totals.toFixed(2)}`; 
    })
    
    它应该可以运行,但是不能运行代码,看看它是否真的运行或者抛出错误,调试它等等。我不能给你100%。 如果出现任何错误,请尝试自己解决:) 如果您遇到困难,请回来告诉我哪里出了问题,哪里出了问题,我会再次尝试帮助您:)

    一般性意见
    • 您的方法名为
      getAttendars
      ,它的作用远不止于此(获取助理)。它获取数据,创建表的一部分,并用数据填充该表。不应该。方法应该只做一件事(单一责任原则),并正确命名
    • 您应该在几个函数之间划分职责,并在它们之间传递数据,允许每个函数只处理一个任务
    前。 -函数A-获取数据 -函数B-创建表 -函数C-用数据填充该表

    在这些函数中,您可以将代码拆分为更小的函数。 在您放置注释的地方,您可以使用内部包含注释代码的函数,并且只需按名称,它们将向开发人员解释它们的工作。 前

    下面的三行用于每个循环中,仅用于访问该运行单元

    const table = document.querySelector('.table');
    const attendantRow = table.querySelectorAll('tr')[index];
    const runningTotalCell = attendantRow.querySelectorAll('td')[2];
    
    您可以提取它们并使用单独的函数进行包装:

    getRunningTotalCellForRow(rowIndex) { 
        const table = document.querySelector('.table');
        const attendantRow = table.querySelectorAll('tr')[index];
        return attendantRow.querySelectorAll('td')[2];
    }
    
    并在forEach循环中使用

    等等

    一般来说,要学习正确的编码方法,您可以学习一些教程、阅读一些书籍并了解规则:)

    至于书籍,罗伯特·C·马丁(Robert C.Martin)的《干净的代码》(Clean Code)就是其中一部经典之作。 至于教程和其他在线资源

    在浏览器中搜索您选择的文本,如: -如何编写干净的代码 -单一责任原则 -干吻固体 -关键软件开发原则

    我认为,从你会发现的网站上,你可以找到更多,并进入其中

    祝你好运,玩得开心

    编辑代码后: 我检查了你的截图。红色部分告诉我,在第一行中,在第二个单元格中插入总计(约32k),它是该值,但在第三个单元格中是该值的两倍,乘以三。这就得出了一个结论,即您一定是弄乱了循环中的一些附加内容

    所以

    您在上面所做的工作:

  • 您定义了var total=0(并且从不使用它)

  • 每4个单元格

  • 带上所有服务员,并为每个服务员

  • 将其
    total
    值添加到此.total中

  • 并将其插入innerText

  • 你现在明白了吗?为每个单元格插入所有助理的汇总总数(加上您已有的这个.totals值,因为您从不将其归零)

    正确版本如下:

    const runningTotalCells = document.querySelectorAll("td:nth-child(4)");
    //no need for nested loops
    this.attendantNames.forEach((attendant, index) => {
      this.total += a.total;
      runningTotalCells[index].innerText = this.total;
    })
    

    现在行了吗?

    你的答案很漂亮,显然行得通。但是我需要使用纯JavaScript。你能把这个函数放在我函数的上下文中吗?我的意思是编辑答案以包含整个getAttendars()函数。非常感谢。@CMazz请现在再试一次。我只处理了
    forEach
    loop,它应该会取代你的loop谢谢。我已经编辑了我的帖子。如果你有时间,也许你可以看看。再次感谢。我再次感谢你的评论。我很感谢您通过的见解。@CMazz检查最后一部分,如果我帮助过您,请将其标记为答案:)。所有的部分都在这篇文章里,你只需要小心和精确:)祝你好运
    var total = 0;
    document.querySelectorAll("td:nth-child(4)").forEach((cell, index) => {
      this.attendantNames.forEach(a=>{
        this.total += a.total;
      });
      cell.innerText = this.total;
    });
    
    const runningTotalCells = document.querySelectorAll("td:nth-child(4)");
    //no need for nested loops
    this.attendantNames.forEach((attendant, index) => {
      this.total += a.total;
      runningTotalCells[index].innerText = this.total;
    })