【问题标题】:Javascript calculation is not working as expectedJavascript 计算未按预期工作
【发布时间】:2023-03-20 07:51:01
【问题描述】:

我有一个gridview,其中有一行我添加了整数值,例如7000

因此,如果添加了 2-3 行,我想添加所有这些行值并将其显示在 textbox

为此,我编写了以下代码

if (document.getElementById('txtTotalExp').value == "") {
            var Expense = 0;
        } else {
            var Expense = document.getElementById('txtTotalExp').value;
        }
        for (var i = 0; i < GridExpInfo.Rows.length; i++) {
            var totAmount = GridExpInfo.Rows[i].Cells[7].Value;
            var totval = totAmount;
            Expense += parseInt(totval);
        }

document.getElementById('txtTotalLandVal').value = parseInt(TotalPayableValue) + parseInt(Expense);

但是在文本框中会出现这样的情况 200010001512

加法操作无效。

【问题讨论】:

  • 而不是 document.getElementById('txtTotalExp').value;使用 parseInt(document.getElementById('txtTotalExp').value,10) 并确保使用 parseInt(value,10) 10 作为基数,以将某些特殊值转换为十六进制,以 10 为基数进行计算
  • 请创建minimal reproducible example,以便我们查看可能出现的问题。我们无法仅使用该 javascript 来验证发生了什么。
  • PascalCase 应该只在构造函数中使用,避免在任何其他类型的类型上使用它。
  • @VinodLouis:让我试试看这个
  • @VinodLouis: 在这一行Microsoft JScript runtime error: Cannot assign to a function result 出现错误parseInt(document.getElementById('txtTotalLandVal').value) = parseInt(TotalPayableValue) + parseInt(Expense);

标签: javascript asp.net gridview


【解决方案1】:

我将您的问题解释为您有一个包含值行的表,您想对每一行求和,然后您想获得整个表的总和。

我想提供一个工作代码 sn-p 来演示您的问题的解决方案。但是,因为您没有提供所有必要的代码,所以我发明了其中的一些。在这样做的过程中,我提供了一种替代方法,也许是更现代的方法来解决我认为您试图解决的整体问题。是的,它提供的远比您所要求的要多(...我认为讨论 parseInt 的其他一些答案可能会解决您最初的问题),但希望这能给您一些进一步的见解。

下面的示例展示了如何使用 JavaScript 的许多最新功能来做到这一点。希望 cmets 足够详细地解释每一步发生的事情,以便您了解逻辑。要理解每一步,您可能需要更深入地学习更多 JavaScript。 Mozilla Developer Network (MDN) 是一个很好的参考,其中包含有关所有这些功能的文档。

// when the button is clicked, do the following...
document.querySelector('button').onclick = () => {

  // calculate the total sum across the table
  const rowSums =

    // get a nodeList of all table rows in the entire document
    // and convert that array-like nodeList to a true array
    // of table row elements
    [...document.querySelectorAll('tr')]

      // remove the first row, i.e. ignore the row of column headers
      .slice(1)

      // from the original array of table rows (minus the first row)
      // create a new array in which each element is derived
      // from the corresponding table row from the original array
      .map(row => {

        // calculate the sum of values across this row
        const rowSum =

          // get a nodeList of all table cells in this row
          // and convert that array-like nodeList to a true array
          // of table cell elements
          [...row.querySelectorAll('td')]

            // remove the last cell, i.e. ignore the cell that will eventually
            // hold the sum for this row
            .slice(0,-1)

            // from the array of table cells for this row (minus the last one)
            // derive a new single value by progressively doing something
            // for each cell
            .reduce(

              // for each table cell in this row, remember the cell itself
              // as well as the accumulating value we are gradually deriving from all
              // the cells in this row, i.e. the sum of all values across this row
              (accumulatingRowSum, cell) =>

                // for each cell in this row, add the numerical value
                // of the current cell to the sum of values we are accumulating
                // across this row
                accumulatingRowSum + parseInt(cell.innerHTML, 10),

              // start our accumulating sum of values across this row with zero
              0
            );

        // get all the cells in this row
        const rowCells = row.querySelectorAll('td');

        // put the sum of values from this row into the last cell of the row
        rowCells[rowCells.length - 1].innerHTML = rowSum;

        // place the sum of values in this row into the accumulating array
        // of all such values for all rows
        return rowSum;
  });
  
  // calculate the total sum for the whole table
  const totalExpenses =

    // start with the array of sums for each row
    rowSums

      // similar to `reduce` above, reduce the array of multiple row sums
      // into a single value of the total sum, calculated by adding together
      // all the individual row sums, starting with zero
      .reduce((accumulatingTotalSum, rowTotal) => accumulatingTotalSum + rowTotal, 0);

  // place the total sum into the appropriate span element
  document.querySelector('#txtTotalExp').innerHTML = totalExpenses;
};
table {
  border: solid black 1px;
  border-collapse: collapse;
}
th, td {
  border: solid black 1px;
  padding: 0.5em;
}
<table>
  <tr><th>col1</th><th>col2</th><th>row total</th></tr>
  <tr><td>3500</td><td>1200</td><td></td></tr>
  <tr><td>2700</td><td>4500</td><td></td></tr>
  <tr><td>3100</td><td>1300</td><td></td></tr>
</table>
<p>The total expenses are: <span id="txtTotalExp"></span></p>
<button>Calculate</button>

【讨论】:

  • 感谢 Andrew 的回答,但现在我可以使用其他代码进行管理。如有需要,将向您寻求帮助
【解决方案2】:

您可以使用以下代码:

var total=parseInt(TotalPayableValue,10) + parseInt(Expense,10);
    document.getElementById('txtTotalLandVal').value=total;

【讨论】:

    【解决方案3】:

    试试这个:

    var Expense = 0;
    if (document.getElementById('txtTotalExp').value != "") {
     var Expense = parseInt(document.getElementById('txtTotalExp').value);
    }
    for (var i = 0; i < GridExpInfo.Rows.length; i++) {
     var totAmount = GridExpInfo.Rows[i].Cells[7].Value;
     Expense += parseInt(totAmount);
    }
    

    问题:费用最初可以是一个字符串。您是否尝试过“Expense = 0”出现错误?

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2020-04-10
      • 2016-03-28
      • 1970-01-01
      相关资源
      最近更新 更多