Increment when calling javascript function

0

Hello.

I would like every time I call the function to be incremented the value of (i) and displayed in the alert, I do not know what I'm doing wrong.

My code;

function incrementar()
{
var count = 0.
count++;
alert(count);
}

Thank you

    
asked by anonymous 21.10.2016 / 01:30

2 answers

0

The function will always display the value 1 , because the algorithm is setting the value of the count variable to zero each time the function is executed.

You can solve the problem as follows:

var count = 0;
function incrementar() {
  alert(++count);
}
    
21.10.2016 / 02:55
2

You are resetting the counter every time you call the function, because it is opening var count inside. Set count before, as in the example, so that the same variable is available whenever it is called.

var count = 0;
    
function incrementar() {
    count++;
    // use console.log ao invés de alert para ver os resultados 
    // no console do navegador, aperte F12 no Chrome para ver o console.
    console.log(count); 
}

incrementar();
incrementar();
incrementar();
incrementar();
    
21.10.2016 / 02:04