Cycle setting



  • How can the sum of all values between the engines be deducted according to their number in the cycle?

    e.g. 5 divAnd they need to be spied. Cycle, I think we need a number of blocks to change.

    <div class="amount"> 1 </div>
    <div class="amount"> 2 </div>
    <div class="amount"> 3 </div>
    <div class="amount"> 4 </div>
    <div class="amount"> 5 </div>
    

    js

    window.onload = function(){
        var text = document.getElementsByClassName('amount');
        for (var i = 0 ; i < text.length; i++){
            sum = ++(text[i].innerHTML);      //тут не ясно 
          console.log(sum);
          }
    }        
    


  • In order to obtain one (the sum in this task), there is a remarkable method of mass https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce ♪

    Okay. getElementsByClassName() It's not a mass, it's an object NodeList, it needs to be converted into a mass, and then applied. reduce() with a function that adds value to the &quot; current &quot; value from another inlet div'a.

    The conversion of a massive object into a mass can be such a trick:

    var myArray = Array.prototype.slice.call( massivoPodobnyObject)
    

    As a result, the general code would look like:

    function pluser(){
      var els = document.getElementsByClassName('amount');
      return Array.prototype.slice.call(els).reduce( addMe, 0);
    }
    

    function addMe(p,c,i,a){
    // p - предыдущее значение общей суммы, c - очередной элемент массива
    return p + parseInt(c.textContent);
    }

    window.onload = function(){
    document.getElementById('total').innerHTML = '<div>Итого: ' + pluser() + '</div>';
    }

    <div class="amount"> 1 </div>
    <div class="amount"> 2 </div>
    <div class="amount"> 3 </div>
    <div class="amount"> 4 </div>
    <div class="amount"> 5 </div>

    <div id="total"></div>


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2