Min / max limit for javascript variable

I am trying to make a talent calculator by clicking "skill", will decrease this variable and right-clicking will increase this variable.

The problem is that I want the variable to be limited to more than 50 or below 0.

Now ive googled and searching here for variable constraints and maximum integers, but nothing gives me an idea of ​​how to do this, I think that the incorrect wording of my searches is incorrect.

Can someone give me an idea how to do this or point me in the right direction, please, thanks.

Im variable using:

var a=50; function decrease(){a--;document.getElementById('boldstuff').innerHTML= +a;} function increase(){a++;document.getElementById('boldstuff').innerHTML= +a;} 
+4
source share
6 answers

In the decrease function after a-- add

 if (a < 0) a = 0; 

And in increase :

 if (a > 50) a = 50; 

Or use Math.min(value, minValue) and Math.max(value, maxValue) .

+2
source

You can use Math.min and Math.max.

  var a=50; function decrease(){ a = Math.max( a-1,0) ; document.getElementById('boldstuff').innerHTML= a;} function increase(){ a = Math.min( a+1,50); document.getElementById('boldstuff').innerHTML= a;} 
+2
source

Try the following:

 var a=50; function decrease(){ if(a > 0){ a--; document.getElementById('boldstuff').innerHTML= +a; } } function increase(){ if(a < 50){ a++; document.getElementById('boldstuff').innerHTML= +a; } } 
0
source

Try the following:

  var a=50; function decrease(){if(a>0){a--;document.getElementById('boldstuff').innerHTML= +a;}} function increase(){if(a<50){a++;document.getElementById('boldstuff').innerHTML= +a;}} 
0
source

Just check the value before you change it, to change it only if it has not reached the limit:

 var a=50; function decrease(){ if (a > 0) { a--; document.getElementById('boldstuff').innerHTML = a; } } function increase(){ if (a < 50) { a++; document.getElementById('boldstuff').innerHTML = a; } } 

(The above code assumes integer values. If you assign 49.9 variable and call increase , it will increase that variable to 50.9 . If you also need to protect against floating point numbers such as if (a - 1 >= 0) and if (a + 1 <= 50) .)

0
source

//// your maximum ///// your min. if (type> 4) {type = 4;} if (type <0) {type = 0;}

just if its outer border is either attached to that border

-1
source

Source: https://habr.com/ru/post/1434181/


All Articles