Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

javascript - how to get change total sum foreach

I have a code cannot get inner foreach total sum

<script>
  const opSelect = document.querySelectorAll('.op .qltbox');
  opSelect.forEach(opSelect => {
    const a = opSelect.querySelector('input[type=text]');

    a.onchange = function() {
      const numTot = parseInt(a.value);
      const itemTot = 0;

      numTot.forEach(eachItem => {
        itemTot += itemTot;
      });
    };
  });
</script>

the second foreach is no function

question from:https://stackoverflow.com/questions/65557467/how-to-get-change-total-sum-foreach

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can store the previous value of each input in the closure and add the delta to the total sum each time it changes.

const opSelect = document.querySelectorAll('.op .qltbox');
let sum = 0;
opSelect.forEach(opSelect => {
    const a = opSelect.querySelector('input[type=text]');
    let prev = 0;
    a.onchange = function() {
        let curr = +a.value;
        sum += curr - prev;
        prev = curr;
        console.log('total sum:', sum);
    };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...