JavaScript not recognizing variable - javascript

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

Related

Creating and overwriting variables dynamic per user input

In the following code, the user is able to create variables utilizing the window object via an input type text element. I've written a function that console logs the name of the variable followed by the value of 0 in which the variable is initialized. This only occurs when the following key string literal, "-nr " precedes the desired name for the created variable.
The goal of this exercise is to increment any created variable value by 1 when the variable name is reentered into the input element. My attempt at doing so is by first writing the first function, varCreate to declare and initialize variables to 0, push them into an array, and console log the variable name followed by its value. The next function which I have a problem with (varPlus) is meant to add 1 to the value of each value when a particular name is entered into the input element however, it adds a few more than 1 even when I utilize a for loop to evaluate if the string literal value of the input element value property is equivalent to each element of the array varArray.
const _in = document.getElementById('in');
var varArray = [];
function varCreate(e) {
let _key = e.key;
if(_key === "Enter") {
if(_in.value.substring(0, 4) == "-nr ") {
window[_in.value.substring(4).replace(/\s/g, "_")] = 0;
varArray.push(_in.value.substring(4).replace(/\s/g, "_"));
console.log("var: " + varArray[varArray.length - 1] + "\nvalue: " + window[varArray[varArray.length - 1]]);
_in.value = "";
}
}
}
function varPlus(e1) {
let _key1 = e1.key;
if(_key1 === "Enter") {
checker = new RegExp(_in.value.replace(/\s/g, "_"), "gi");
for(var i = 0; i < varArray.length; i++) {
if(checker.test(varArray[i])) {
window[varArray[i]] += 1;
console.log("var: " + varArray[i] + "\nvalue: " + window[varArray[i]]);
}
}
delete window["checker"];
}
}
_in.addEventListener('keydown', varCreate);
_in.addEventListener('keydown', varPlus);
<input id='in' type='text' />
The end result when attempting to utilize varPlus is that it'll console log all variable names and values which somehow increment in value when it should only be console logging only the variable name which I'm trying to access via user input followed by its value. I would greatly appreciate it if anyone can shed some light on how I'm encountering these errors.
First of all it is really helpful if you try and make your code executable :)
Now for the user generated variables you could do something like this:
// DOM Elements
const input_variable = document.getElementById("input_variable");
const button_createVariable = document.getElementById("button_createVariable");
// Variables
let userVariables = {};
// Event listeners
window.addEventListener("keyup", event => {if(event.key == "Enter") parseVariable()});
button_createVariable.addEventListener("click", parseVariable);
function parseVariable() {
// Get the variable name and remove all spaces
let variableName = input_variable.value.substring(0, input_variable.value.indexOf("=")).replace(/\s+/g, '');
// Get the variable value and remove all spaces
let variableValue = input_variable.value.substring(input_variable.value.indexOf("=") + 1, input_variable.value.length).replace(/\s+/g, '');
// Add the variable to the object
userVariables[variableName] = variableValue;
// Clear the input
input_variable.value = "";
// Log the object into the console
console.log(userVariables);
}
<input id='input_variable' type='text'/><button id="button_createVariable">Create</button>
WARNING You of course still need to verify the user input. At this state it will accept everything as input. But now you can loop through the object and count up (or whatever) if already exists.
Oh yes btw, the syntax is simply: <name> = <value> eg. foo = 10.. unimportant detail :P

if else preventing loop for passing through object

I am having trouble returning a statement when my RegExp finds no matches :
function ai(message) {
if (username.length < 3) {
username = message;
send_message("Oh, well hello " + username + ", My name is Donald J Trump and i'm a big boy");
} else {
for (i = 0; i <= botChat.length; i++) {
var re = new RegExp(botChat[i][0], "i");
if (re.test(message)) {
var length = botChat[i].length - 1;
var index = Math.ceil(length * Math.random());
var reply = botChat[i][index];
send_message(reply);
}
}
}
}
When I enter a phrase it can correctly match the first line in an array as per the for loop. The issue I'm having is when I try to add an else statement it ceases to loop through my array properly.
I have tried :
else if (re.test(message) === false) {
send_message("i can't be expected to know everything");
}
But it doesn't work, it prevents the loop from looping past botChat[0][0].
I've also tried :
if (send_message().val() == "") {
// ...
}
But every time my code no longer works. Is there a method of adding something to my array that says 'if you don't find a match above, choose this'?
Or just a way of working my code so that the if/else works?
attached is the codepen.
I checked your codepen and the lines 190 and 194 console.log(send_message().val()); seems to be breaking the loop because those lines are throwing an exception since send_message() returns undefined and undefined does not have the .val() method.
Your regular expressions are working fine. I recommend not creating new RegExp objects every iteration, instead, use the one defined in the array if (botChat[i][0].test(message)), the overhead will be less.

Declaring a for loop function in javascript

I have a for loop that searches for a value in an array in my javascript code in couchDb. I want to make it into a function. This should be fairly simple but I am having trouble with it. This is the for loop(Which works perfectly fine):
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].address) return;
}
}
throw({forbidden: 'doc.address is required'});
And this is the way I wrapped it into a function:
function arrayReq(field, message) {
message = message || "Array must have a " + field;
if (newDoc.destination && newDoc.destination.length > 0) {
for (var i = 0; i < newDoc.destination.length; i++) {
if (newDoc.destination[i].field) return;
}
}
throw({forbidden: message});
}
I would think that the return in the function should stop the function from going any further but it still throws the error. Can someone tell me what I am doing wrong? Btw if i change field into address it works fine. Can I not make the address into a changeable variable?
I think the problem is that you are trying to use field as both a string variable, and a property of your object inside the destination[] array.
In your code, if the destination[i] object does not have a property called field (not the string value populated in the field parameter, but an actual property named "field") it will never evaluate to true and break out of the function.
To access a property of an object by using the string representation in javascript, you use the indexer syntax.
Try changing it from array.destination[i].field to array.destination[i][field]

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?

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.

Categories

Resources