How To Change A Global Variable With An If/else Statement
Solution 1:
Because your n
is also a parameter in the function. So it hides the outer variable n
in the function
and when you access the n
, it refers to the parameter variable
. To work with the global n
, you need to remove the parameter, or change it's name.
function betInput(thisRoll) {
var x;
if (thisRoll === 'green') {
x = base_bet;
n = 0;
} else {
n = n + 1;
}
return x;
}
Solution 2:
The function betInput(thisRoll, n)
contains a parameter n
which shadows the global variable n
. Calling that function using betInput(thisRoll)
merely sets the local n
to a default value.
(The fact that Javascript is lax on this - and many other things - does make it difficult to write stable code in the language).
Simply remove n
from the function parameter list and all will be well.
Solution 3:
Remove the parameter in your function. There's n
there, which makes it scoped to the function.
function betInput(thisRoll, n) {
//------------------------^^^
Change your function to:
function betInput(thisRoll) {
So that, n
will reference your global variable, otherwise n
is undefined in your function scope
Post a Comment for "How To Change A Global Variable With An If/else Statement"