javascript 我如何添加两个For语句值

mfuanj7w  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(100)

我想在for语句中添加两个值

resultSum.value = number_format(parseInt(productAmount.value));
resultSum.value = number_format(parseInt(localAmount.value));

但是,分开求和
如何计算产品金额. value+本地金额. value之和?
一个二个一个一个
如果做这个代码,它可以添加,但不能productAmount. value + productAmount. value/localAmount. value + localAmount. value你能给我一个最好的解决方案吗?谢谢!

vuktfyat

vuktfyat1#

我想我理解了一组复选框的单击处理程序如何包含另一组复选框的单击处理程序的结果,答案是将处理程序中的计算代码 * 因子化 * 为两个复选框共享的函数。
(1)Factor 将数学分解成只做数学运算的函数,如下所示(可以对这些函数进行更多的改进,但我保留了大部分不变,以便OP可以识别现有的逻辑...)

// these two functions do only math on numerical values

const computeProductSum = () => {
  let cnt = 0,
    result = 0
  for (let j = 0; j < productChcbx.length; j++) {
    if (productChcbx[j].checked) {
      cnt++;
      if (cnt == 1) {
        result = 70000;
      } else if (cnt > 1) {
        result = 70000 + 60000 * (cnt - 1);
      }
    } else {
      if (cnt == 0) {
        result = 0;
      }
    }
  }
  return result
}

const computeLocalSum = () => {
  let cnt = 0,
    result = 0
  for (let j = 0; j < localCheckboxs.length; j++) {
    if (localCheckboxs[j].checked) {
      cnt++;
      if (cnt == 1) {
        result = 150000;
      } else if (cnt > 1) {
        result = 150000 + 100000 * (cnt - 1);
      }
    } else {
      if (cnt == 0) {
        result = 0;
      }
    }
  }
  return result
}

(2)* 因子 * 接受数值并将其转换为格式化html的能力...

const formatHtml = number => {
  return number_format(number) + "원";
}

(3)排除了这些工具(如果我正确理解了OP的逻辑目标),我们可以在同一个click处理程序中为两种类型的复选框执行数学计算...

// both checkbox types can share this code
const checkboxClick = () => {
  const sum = computeProductSum() + computeLocalSum()
  resultSum.value = formatHtml(sum)
}

(4)将相同的函数附加到所有复选框...

for (let i = 0; i < productChcbx.length; i++) {
    productChcbx[i].addEventListener("click", checkboxClick);
}

for (let k = 0; k < localCheckboxs.length; k++) {
    localCheckboxs[k].addEventListener("click", checkboxClick)
}

EDIT此操作生效后,对数学的改进如下所示:我们需要一个函数,为选中的第一个复选框分配一个数值,为所有其他复选框分配另一个值。

// for the list of checkboxes, compute a weighted sum for the checked ones
const computeCheckboxSum = (list, firstWeight, weight) => {
  const count = list.reduce((sum, el) => sum + (el.checked ? 1 : 0), 0);
  return count ? firstWeight + (count-1)*weight : 0
}

使用它可以大大减少我们之前编写的两个计算函数中的代码...

const computeProductSum = () => {
  return computeCheckboxSum = (productChcbx, 70000, 60000);
}

const computeLocalSum = () => {
  return computeCheckboxSum = (localCheckboxs, 150000, 100000);
}

相关问题