I'm creating a small game as a test for my JavaScript skills. For some reason I cannot figure out, when I compare the variable iron
and the variable drill
, drill
becomes undefined, and listed as NaN
in my webpage.
I'm using Javascript and HTML on repl.it. I feel it may be an issue with my If
statements, but I'm not sure how to fix them if that is the source of the issue. Also, the variables iron
and drill
are set to 0
default.
if (iron < drillPrice) {
alert("Not enough iron");
}
if (iron >= drillPrice) {
drill = drill + 1;
tempDrills = drill
iron = iron - drillPrice;
document.getElementById('drillsOwned').innerHTML = drill;
iron = Math.round(iron * 10) / 10;
document.getElementById('ironOwned').innerHTML = iron;
drillPrice = Math.floor(100 * Math.pow(1.1, drill));
document.getElementById("drillPrice").innerHTML = drillPrice;
}
}
The full repl is here: https://repl.it/@Munix/factory
The output expected if the variable iron
is higher then the variable drillPrice
, it should make drill
one higher, in this case making drill
equal 1
. What actually happens is drill
becomes undefined
. If the variable iron
is lower than drillPrice
, it should display the test Not enough iron
, and not touch the variable drill
. What actually happens is it displays the test Not enough iron
, but sets drill
to undefined
.
The issue is this part of the code:
function randomEvent() {
var event = Math.random();
event = Math.round(event * 10);
if (event <= 9) {
document.getElementById("event").innerHTML = "No event today!";
drill = tempDrills
}
if (event == 10) {
var eventFlavor = 'You have iron deficiency! 1/2 iron from drills for the rest of the day!';
document.getElementById("event").innerHTML = eventFlavor;
var tempDrills = drill;
drill = drill / 2;
}
}
What we see here, is an example of how variables are created in javascript: var tempDrills = drill;
The declaration of the variable is hoisted to the top of the function, so it basically looks like this:
function randomEvent() {
var event = Math.random();
var tempDrills;
...
}
So the variable gets hoisted and will not be set to the value of drill
, unless you are lucky enough to roll the 1 in 10 on startup. So tempDrills
is a local variable with the value undefined in the other 9 cases, explaining the behaviour once you set drill
back to tempDrills
.
The solution is silmply to remove the var
keyword, so you use the global variable instead. Then it works as expected for me.
drill = tempDrills
at the incorrect time, causing it the variable drill
to become undefined
.
By removing this, I managed to get the code to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.