How to calculate values within arrays?

Asked

Viewed 581 times

1

I have the following algorithm to perform the calculation of a Polish reverse calculator.

function  pilhaNumeroVisor() {
  var pilha = [] ;
  var num = document.calcform.visor.value;
  if(num != "" ) {
    pilha.push(num);
    document.calcform.visor.value = "" ;
  }
  if (num == "" ) {
    resultado = pilha[0] + pilha[1];
    document.calcform.visor.value = resultado;

  } 
} 

What was to return in a input the sum result, returns NaN. Can someone help me? Thank you in advance!

1 answer

1


Will always give NaN because you are declaring the array within the function; therefore, each time the function is called, the array will be empty because it is redeclared.

Another point is: if you try to add the first two indexes of the array and one of them does not exist, it will result in NaN also.

You can use the method .reduce() to add together the array elements as you add values.

See how it would look (explanatory comments in the code):

// declara a array fora da função
var pilha = [];

function  pilhaNumeroVisor() {

   // declara a variável "resultado"
   var resultado;
   var num = document.calcform.visor.value;

   if(num != "" ) {
      
      // adiciona o número na array em tipo "number"
      pilha.push(Number(num));
      document.calcform.visor.value = "" ;
   }

   if(num == "" ) {

      if(pilha.length){
         // altera a variável somando os valores
         resultado = pilha.reduce(function(a,b){
            return a + b;
         });
      }

      // o visor só vai receber valor se resultado for válido
      document.calcform.visor.value = resultado || '';
   } 
   
}
<form name="calcform">
   <input type="text" name="visor">
   <button type="button" onClick="pilhaNumeroVisor()">OK</button>
</form>

Now, you can also use this more streamlined code:

var pilha = [];

function pilhaNumeroVisor(){

   var resultado,
   vis = document.calcform.visor,
   num = vis.value;

   if(num){
      pilha.push(Number(num));
      vis.value = "";
   }else if(pilha.length){
      resultado = pilha.reduce(function(a,b){
         return a + b;
      });
   } 
   vis.value = resultado || '';
}
  • Sam thank you so much for the answer! It helped me a lot! But you would know how I would operate all the data that is inside the array?

  • What do you mean? This array will have at most two numbers that will add up. Then it is emptied and so on.

  • Its operation is in two data collected from the array. But by the IF whenever the user enters more number the array will store. So I want to do the same operation only, let’s assume, if the array has 4 numbers? I don’t know if it’s possible! That’s why I ask.

  • So Peraí: you want to go storing the numbers? You can go storing yes. Then you want to add everything as a result?

  • Yes that’s right!

  • Guy now hasn’t founded. He’s not running. I tried to see new ways to do reduce and couldn’t get.

  • Before its last function gave cerro because I just copied and pasted. Logic is correct. But I do not know why not messed this second.

  • Ok. Very obg on the way here! Already helped a lot!

  • 1

    Dude discovered the problem really messed up! VLW!

  • Sam has come up with a bug. This array will run out of values the user has stored. And possible Zera this array right after the result is displayed on the display?

  • Just put pilha = []; after giving a value to the variable resultado, that is, after resultado = pilha.reduce(function(a,b){&#xA; return a + b;&#xA; });

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.