referenceerror treasureHunter not defined? - javascript

so i was programming a javascript program, and for some reason, i got an error saying: ReferenceError: treasureHunter not defined
I searched all over the internet for this info, but although this has been answered many times, their answers don't fit specifically to the problem in the code.
Here's the code:
// Sets a global variable for loot. Global variables exist outside functions or conditional statements. Local variables exist within those things.
global loot = 0;
// alert(loot);
// Creates a function called treasureHunter(). We don't put anything in the parenthesis, but we will later for other functions.
function treasureHunter() {
//Creates a local variable inside treasureHunter called treasureSuccess equal to Math.random(). Math.random is bult into JavaScript, and creates a random number between 0 and 1, e.g. .456 or .99. We use this to create excitement in an otherwise dull and boring existence.
var treasureSuccess = Math.random();
//Here we create a local variable called closedChest equal to the image that we want to pull down from the interwebs when we fail at getting loot.
var closedChest = "<img src='https://s-media-cache-ak0.pinimg.com/736x/eb/c7/84/ebc784ae55857b1470767c4747eb0715.jpg' length='285px' width='285px'>";
//Here we create a local variable called openChest equal to the image that we want to call up when we succeed - YES!
var openChest = "<img src='https://slm-assets1.secondlife.com/assets/1545906/lightbox/e6cfd0355756301c0f6f6d666e75c3de.jpg?1277247329' length='285px' width='285px'>";
var dragon = "<img src='http://orig06.deviantart.net/dd94/f/2012/112/c/b/cb9da88db9660edea4746e95df8fa4ed-d4x7orn.jpg' length='285px' width='285px'>";
//Here we create a conditional statement that asks if the variable treasureSuccess is greater than 5. This is called a boolean operation, it can be answered yes or no. This will of course be random, since treasureSuccess is equal to Math.random() - see above.
if (treasureSuccess > .5) {
//Here we tell the conditional statement what to do if it evaluates true, in other words, if Math.random() happens to be greater than .5. This will change the element using treasureChest, our DIV above in our HTML to the openChest variable, which is set to the image of an open chest. Go figure :)
if (treasureSuccess > .9) {
//dragon time!!
document.getElementById("TreasureChest").innerHTML = dragon;
//dragon image
loot = 0;
//loot reset
document.getElementById("Loot").innerHTML = "You lost all your gold!";
}
}
else {
document.getElementById("TreasureChest").innerHTML = openChest;
//This adds 100 to the global variable loot, each time we are successful, or each time treasureSuccess is greater than .5
loot = loot + 100;
//This tells the loot ID selector to update, so we can see how much gold we've got. THis uses the updated value for loot, which is why it is written below the loot = loot +100 line.
document.getElementById("Loot").innerHTML = "You've got" + " " + loot + " " + " gold";
//waits 500 milliseconds
setTimeout(treasureHunter,500);
document.getElementById("TreasureChest").innerHTML = closedChest;
//reputs the picture
}
//this is the end of the conditional statement
//This tells the statement what to do if the conditional statement evaluates to false, or if treasureSuccess is less than .5. You get a chest slammed shut in your face son.
else document.getElementById("TreasureChest").innerHTML = closedChest;
}
//this is the end of the function
I call it like this:
<div onclick="treasureHunter()" align="center" id="TreasureChest">
<img src="https://s-media-cache-ak0.pinimg.com/736x/eb/c7/84/ebc784ae55857b1470767c4747eb0715.jpg" length="285px" width="285px">
Any help is appreciated!

There are some syntax errors, so treasureHunter() wasn't defined.
global in global loot = 0; doesn't seem valid. Change it to var or something.
else in else document.getElementById("TreasureChest").innerHTML = closedChest; is invalid since there are no corresponding if. Remove it or fix the code properly.

Related

Conditional statement is not recognizing variable values

I am making a simple reaction time game for a final project.
We are using javascript to power the functions in the game, most of my code is in working order, but I have an if conditional statement that's giving me trouble.
Here's the code
function fireTime() {
setTimeout(ShotsFired, time);
function ShotsFired() {
fire.style.visibility = "visible";
createdTime = Date.now();
console.log(createdTime);
EnemyTime = Math.floor((Math.random() * 1000) + 400);
setTimeout(EnemyShoot, EnemyTime)
function EnemyShoot() {
console.log(EnemyTime);
gameplay();
}
function gameplay() {
reactionTime = -(createdTime - clickedTime);
var EnemyTime;
console.log(reactionTime);
if (reactionTime < EnemyTime) {
alert("Wow you beat him! Congrats!");
fire.style.visibility = "hidden";
clickedTime = 0;
createdTime = 0;
reactionTime = 0;
scavnumber++;
BGnumber++;
DesertBG.src = "images/Desert" + BGnumber + ".png";
scav.src = "images/scav" + scavnumber + ".png";
fireTime();
} else {
EndScreen.style.visibility = "visible";
}
}
This is not the entire code, just the function that should progress the game to the next level.
For whatever reason, even though reactionTime is less than EnemyTime, the EndScreen becomes visible.
Anyone know what could cause this?
Use floating point for your enemy time maths, i.e. 400.0 , else you are getting 0/1 seconds and not using milliseconds, and it is useing Math integer. Specifically cast your enemyTime as a float number, for the moment, if you print it it's probably an integer. its a MAJOR js coding detail that you will cost you hours of bughunting in the future if you think that 101/50 = 2.05, it isn't it equals 2, so divide by 50.0 and same with all second/ms tasks.
Use EnemyTime as a global variable for all scripts, at the moment, the code things you have a different function called EnemyTime in all scripts, the latter one has no value.
Use print to see when your else conditions work, specify a print in both an print the enemyTime value.
That's how you are supposed to resolve the issue, by printing the variables that are confusing.

JavaScript and Array's

EDIT I originally posted this with my version of the J.S but it's so far off no one can even help so i'm starting over. Here is the pseudocode i have done that needs to be translated into a Javascript program. Any help is appreciated!
I am a beginning programmer i understand this code will have multiple errors, that's why i am here. Array's and loops have given me much trouble while trying to learn them and especially with formatting them in JavaScript. The things i know are incorrect or still need i commented out i still need them, i also know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated.
Module main()
//Declare local variables
Declare endProgram = “no”
While endProgram == “no”
Declare Real notGreenCost[12]
Declare Real goneGreenCost[12]
Declare Real savings[12]
Declare String months[12] = “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”
//function calls
getNotGreen(notGreenCost, months)
getGoneGreen(goneGreenCost, months)
energySaved(notGreenCost, goneGreenCosts, savings)
displayInfo(notGreenCost, goneGreenCosts, savings, months)
Display “Do you want to end the program? Yes or no”
Input endProgram
End While
End Module
Module getNotGreen(Real notGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module getGoneGreen(Real goneGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter GONE GREEN energy costs for”, months[counter]
Input goneGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module energySaved(Real notGreenCost[], Real goneGreenCost[], Real savings[])
Set counter = 0
While counter < 12
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo(Real notGreenCost[], Real goneGreenCost[], Real savings[], String months[])
Set counter = 0
While counter < 12
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
A few notes:
Currently the program creates a few variables and functions that
don't seem to interact
Most of the edits below are not optimal - there are parts that
could be done by much simpler means (i.e. counter++) - But thats
for you to learn =P
I made quite a few assumptions of what you wanted the program to
do, they might be wrong, they might be right
var notGreenCost = []; //Array lengths don't need to be specified
var goneGreenCost = [];
var savings = [];
var months = ["January", "Feburary", "March", "April", "May", "June"];
//A boolean value (true | false) would suit this better as opposed to "yes"/ "no"
var endProgram = false;
var option = 0;
/* You dont need main functions in javascript
* migrated everything to be global :/
* Delete:
function main(){
// Move this (made it global): var endProgram = "no";
}
*/
// I don't think this is meant to be initMonths..
// Maybe something like getOptions?
function /*initMonths*/getOptions(){
while (endProgram == false){ //lowercase while
//Because prompt would block everything else until it gets input
//we probably want to move the prompt to be after the alerts
alert("options:"); //Clarity
alert("1 to enter data");
alert("2 to display data");
alert("3 to write data to a file");
alert("4 to read data from a file");
//Alter global "option" to take the value of the prompt
option = prompt("What would you like to do? Type:");
//} //I assume you want the rest of the code in this while loop - otherwise it will loop forever
// Delete this bracket (its unmatched): {
// Delete return statement as it will stop the function return option;
// Delete this bracket (its unmatched): }
//Create a variable to take the value of prompt (this should be outside the while loop) but it seem clearer for explanation purposes to be here
var toEnd;
toEnd = prompt("Do you want to end the program (enter yes or no)");
// Javascript uses != for "not equal to" and && for "AND"
while (toEnd != "no" && toEnd != "yes") {
toEnd = prompt("Please enter a value of yes or no");
}
//I think you want to assign the value of toEnd to endProgram
// Note the the below is not the only/best way to do it
if(toEnd == "no") {
endProgram = false;
} else if(toEnd == "yes") {
endProgram = true;
}
// While use brackets not End s
// End While
// End While
}//End while loop here
}
Javascript in a browser cannot alter files - writeToFile, readFromFile have all been removed
I believe you want months to be global, if it is then initMonths is unnecessary
getNotGreen:
function getNotGreen(){
//You don't need to specify types in Javascript
/*Integer*/ var counter = 0
while (counter < 6){ //lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
notGreenCost.push(prompt("Enter NOT GREEN energy costs for" + months[counter]))
//Returning here makes the rest of the function redundant
//}
//return notGreenCost[counter];
//}
//Javascript does not use Set
// Note that below is not the only/best way to do it
/*Set*/ counter = counter + 1
} //End the while loop here
}
getGoneGreen:
function getGoneGreen(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
goneGreenCost.push(prompt("Enter GONE GREEN energy costs for" + months[counter]));
//See above (getNotGreen)
//}
//return goneGreenCost[counter];
/*Set*/ counter = counter + 1;
}//End while loop here
}
energySaved:
function energySaved(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
savings[counter] = notGreenCost[counter] - goneGreenCost[counter]
counter = counter + 1;
}
} //I assume you want to end energySaved here?
displayInfo:
function displayInfo(){
//Alert produced individual boxes, i assume you want the following in a single window?
// "\n" is a line break
alert("SAVINGS NOT GREEN GONE GREEN MONTH\n"+
"_________________________________________________\n");
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
alert( "$" + savings[counter] + "$" + notGreenCost[counter] + "$" + goneGreenCost[counter] + "" + months[counter]);
counter = counter + 1;
}
} //I assume you want to end displayInfo here?

JavaScript not recognizing variable

I'm new to Javascript and struggling to figure out why this piece of code isn't working for me.
Essentially I'm defining a variable, yet when I go to use that variable in an IF or Switch statement, it doesn't seem to be able to match the contents of the variable. No errors, the IF statement just doesn't get satisfied. While with the Switch, it always falls through to the default setting, as it can't match the contents.
I have a Print statement in place after the variable is defined, and it does display the contents of the variable correctly.
I'm really at a loss as to why the print can return the value of the variable, yet the IF and Switch can't find it.
Below is the snippet I'm working from. The variable is "strWilma", which doesn't get reflected properly in the Print second value statement, but not in the IF.
for (var i=0; i < Flinstones.length; i++)
{
if (Flinstones[i].startsWith("?"))
{
// Convert the Secondary field map to a Properties item, for easier navigation
var objSecondaryFieldMap = PropertiesFromString(strSecondaryFieldMap);
// Map all of the Secondary values
var arraySecondaryFields = objSecondaryFieldMap.keys();
while (arraySecondaryFields.hasMoreElements())
{
strFred = arraySecondaryFields.nextElement();
strWilma = objSecondaryFieldMap.get(strFred);
print("TargetType:" + Object.prototype.toString.call(strFred));
print("SourceType:" + Object.prototype.toString.call(strWilma));
print("Text Type:" + Object.prototype.toString.call("hardcoded value"));
print("First Value:" + objItem.getNewFieldValue(Flinstones[i].substring(1)) );
print("Second Value:" + strWilma );
if (objItem.getNewFieldValue(Flinstones[i].substring(1)) == strWilma)
//if (objItem.getNewFieldValue(Flinstones[i].substring(1)) == "hardcoded value") // WORKS
{
print("It Worked!!!");
}
}
}
}
}
Thanks

Nested If-else statements being skipped

What I'm building is a game where the computer generates a random number (1-100) and the user must guess the correct number. The goal is for the computer to compare the current guess to the previous guess and spit out a statement: "hot", "cold", "hotter", "colder", etc.
My Code (focus on the JS): CodePen fiddle
//global variables--computer generated guess, and guess log
var answer = Math.floor((Math.random() * 100)+1);
var guessArray = [];
var index = 0;
//user clicks submit button and guess is registered by computer
$("#submit").click( function(){
var guess = $("#guess").val();
guessArray.push(guess);
//prints out the answer and user guesses
$("#answer").text("Answer:" + " "+ answer);
$("#guessArrayPrint").text("You guessed: " + " " + guessArray + " ");
if (answer === guess) {
$("#statement").text("woo hoo right answer");
} else {
var currentDifference = Math.abs(answer-guess);
var currentDiffArray = [];
currentDiffArray.push(currentDifference);
if (index = 0) {
//if-else statement comparing current guess range to answer
if ( currentDifference >=1 && currentDifference <= 10){
$("#statement").text("Ouch! You're hot!");
} else {
$("#statement").text("Brr! You're cold!");
}
} else {
//if-else statement comparing current guess to previous guess
var previousDiff = answer- prevguess;
var prevguess = guessArray [i-1];
if( previousDiff < currentDifference){
$("#statement").text("Ahh! Getting Warmer!");
} else {
$("#statement").text("Brrr...getting colder");
}
}
index++
}
});
My nested if-else statements are not working. When a user inputs a guess, no matter how close to the answer, it always returns the statement "brr.. getting colder", which is in the "else" section.
Ideally when the user inputs their first guess if (index = 0) should run then when the second guess is input, it should move to the "else" statement with the previous guess variables. I tried moving around the variables, changed orders of if/else, and thought maybe it's the placement of index++. Nothing is working. Not sure if something is wrong with my variables , arrays, or the syntax of my if/else statements.
tl;dr: when the program is run only the "else" portion of the nested if-else statement is run. Not sure how to fix… I've gone through my code a number of times. The syntax, the arrays, and variables. Uncertain what's wrong.
You JS has if (index = 0). This should be if (index === 0).
Additionally, you need to cast the value of your input field to a number. You can do this using:
var guess = +$("#guess").val(); // + cast as a number
More syntax errors:
prevguess = guessArray[i - 1] --> prevguess = guessArray[index - 1];
Here is a partial working Fiddle. I ran through some scenarios, and the fiddle really only works if you give the application the right answer. The code has many syntax errors, bad refs and calculations. I would suggest opening the console or a debugger, identifying those issue, and fixing them.
Here is a Fully Functional Demo.

Onclick function for all members of a class

I'm making a two-column math page, with theorems and definitions on the left side, and additional explanations on the right side.
The way that the user accesses the explanations is by clicking on text of the class "explainable".
After the page loads, I run a script to give each "explainable" element its own onclick function, which hides the text on the right panel (if any) and refills it with the clicked's elements explanation.
But when I try and run it, it tells me that the explainable element is undefined.
Here is the relevant function and an example of the text with the class:
function
<script type="text/javascript">
window.setTimeout(makeExplanations, 3000);
function makeExplanations(){
var explainables = document.getElementsByClassName("explainable");
var currentlyShowing = "";
for(var i = 0; i < explainables.length; i++){
console.log("id: " + explainables[i].id);
var element = explainables[i];
explainables[i].onclick = function(){
if(currentlyShowing != ""){
document.getElementById(currentlyShowing + 'e').style.display = "none";
}
var explanationDiv = document.getElementById(explainables[i].id + 'e')
explanationDiv.style.display = "inline";
explanationDiv.focus();
currentlyShowing = explainables[i].id;
};
}
}
</script>
I have it waiting 3 seconds to execute because doing body onload=makeExplainables() wasn't sufficient. (Might have something to do with the way that the MathJax loads - I'm not sure.)
example of explainable class
<span class="explainable" id="595858535">so either statement is vacuously true</span>. Thus, $X = Y$ holds,
and hence we declare that there exists only one set with no elements.</p>
and the explanation it reveals
<div id="595858535e" style="display: none;">
<p>An if-then statement (a conditional) is vacuously true when the if portion is false in all cases.
For example, the statement "If 2 + 2 = 5, then pigs fly" is vacuously true, since its
antecedent (if 2 + 2 = 5) is always false.</p>
<p>In this case, the conditional in question is "there exists some $x \in X$ such that $x \notin Y$".
But since $X$ is an empty set, there does not exist any $x \in X$ such that anything. Hence, the
statement is vacuously true in all cases.</p>
<p>Another way to think about it is this: a conditional is only falsified if its antecedent ("if ...") is true
and its consequent ("then ... ") is false. If the antecedent is always false, then this can never happen.
Thus the statement as a whole is always true.</p>
</div>
Error in Firebug when I try to click on the explainable text:
16:23:44.704 "id: 595858535" zfc:89
16:23:44.704 "id: 595858536" zfc:89
16:23:53.045 TypeError: explainables[i] is undefined zfc:95
The real reason for that error is that "i" has already reached a value equal to the array's length, when the click handler is called. Hence explainables[i], i.e. explainables[explainables.length] is undefinded.
JS fiddle with console logs to explain you better: http://jsfiddle.net/wV4Lh/6/
element.onclick = function(){
// length of array is 2 for this example
console.log("explainables length: " + explainables.length);
// value of i is 2 in the click handler
console.log("i: " + i);
// explainables[i] = explainables[2] is undefined
console.log("explainables[i] - ith: " + explainables[i]);
// explainables[0] is valid
console.log("explainables[0] - 0th: " + explainables[0]);
// explainables[1] is valid
console.log("explainables[1] - 1st: " + explainables[1]);
};
This clearly shows that explainables is well in scope of the click handler, but value of i = length of the array as the 'for' loop has already completed it's full execution way before the click event is triggered.
P.S: The difficulty in initially understanding this behavior of a handler is due the counter-intuitive way a handler works, i.e. it is not executed in sequence with other code surrounding it. A handler only get's executed when corresponding event is triggered and not in sequence with in the for loop, in this case.
So, I finally got it work by changing the explanation[i] in the onclick function to this.
I thought that I was making a closure wherein the explanation[i] variable would be accessible from within the onclick function even after makeExplanations() ended, but I guess that is incorrect.
The corrected onclick function looks like this:
explainables[i].onclick = function(){
if(currentlyShowing != ""){
document.getElementById(currentlyShowing + 'e').style.display = "none";
}
var explanationDiv = document.getElementById(this.id + 'e')
explanationDiv.style.display = "inline";
explanationDiv.focus();
currentlyShowing = this.id;
};

Categories

Resources