Update the value of a variable for the result of its sum with +1

Asked

Viewed 225 times

0

I have a variable that is a number, I want to update its value when the button is clicked... But I want to update the value with sums, for example: the variable value is 0. But when the button is clicked the value updates pro result of the current value (0) summed by 1 (0+1) That is to say, The variable will update the value to 1. And so on.

EXAMPLE HTML CODE:

The code below makes a button that says "grow":

<input type="button" value="crescer" onclick="buttonclick();" />

Now the JAVASCRIPT:

var idade = 0
   
function buttonclick() {
    var eunaosei = "ai era pra estar a solução pra mudar o valor pra soma 0+1, 1+1 e por ai vai.."
}

document.write('Idade:');
document.write(idade);```

2 answers

2

You need increase its variable. For this, there are some different forms:

var n = 0;
function crescer(){
  n++;
}
crescer();
console.log(n); // mostra o valor de n

var n = 0;
function crescer(){
  n += 1;
}
crescer();
console.log(n); // mostra o valor de n

Or else:

var n = 0;
function crescer(){
  n = n + 1;
}
crescer();
console.log(n); // mostra o valor de n

2


To increment a value in Javascript there are four ways. The most common and simple of all is using the operator ++ that will add +1 value of variable. See example below:

var valor = 2;
valor++;

console.log(valor);  // Resultado: 3

The second way is also using the operator ++, but here you must use it before the variable. The difference this way for the first one is that in the first form the value is incremented only after it has been used. See the example below:

var valor = 2;
console.log(valor++); // Imprime 2 porque o incremento vem depois.
console.log(++valor); // Imprime 4 porque o incremento vem antes.

The third way is using the operator += which will increment a value X to the variable. In this form you yourself specify the value that will be added, being quite different from the first way where the sum value is 1 obligatorily.

var valor = 2;
valor += 5;

console.log(valor);  // Resultado: 7

The last form is by assigning to the variable its own value added to another value you want, using the summation operator.

var valor = 3;
valor = valor + 1;

console.log(valor);  // Resultado: 4

As you saw in the example above, both the third and fourth forms are equivalent. So if you want to make your code smaller and more beautiful, use the third way.

Now take this last example which may be what you want:

let value = 0;

function incrementar() {
    document.getElementById("display").innerHTML = `Value: ${++value}`;
}
<input type="button" onclick="incrementar();" value="Incrementar"/>
<div id="display" style="padding-top: 15px;">Value: 0</div>

Browser other questions tagged

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