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?
– Moises Moraes
What do you mean? This array will have at most two numbers that will add up. Then it is emptied and so on.
– Sam
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.
– Moises Moraes
So Peraí: you want to go storing the numbers? You can go storing yes. Then you want to add everything as a result?
– Sam
Yes that’s right!
– Moises Moraes
Guy now hasn’t founded. He’s not running. I tried to see new ways to do reduce and couldn’t get.
– Moises Moraes
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.
– Moises Moraes
Ok. Very obg on the way here! Already helped a lot!
– Moises Moraes
Dude discovered the problem really messed up! VLW!
– Moises Moraes
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?
– Moises Moraes
Just put
pilha = [];
after giving a value to the variableresultado
, that is, afterresultado = pilha.reduce(function(a,b){
 return a + b;
 });
– Sam