Repetitive result in Javascript - javascript

I am currently working with some test codes in Javascript. When I inserted the ..else {} in a IF statement within a for..loop, procedures under else{} should not be run if the statement is TRUE, but it is not happening. The output is always displays the message "No place logged" even the statement is TRUE.
A beginner in Javascript here. :-)
this is the sample code.
function forLoops() {
for (var x = 0; x < places.length; x++) {
if(userInput === places[x]) {
console.log("Your place input " + userInput + " is on our database.");
} else {
console.log("No place logged!");
}
}
}

you are using === and not == which in javascript means equal and no type conversion.
so if userInput is NOT a number but maybe a string of a number "6" insead of 6, than its not equal.
check your function with ==

Solved it!
I should use == not === when declaring variables.
I realized it when trying and testing my code.
Answers above supported my answer.

Here userInput is undefined according to your provided code
Another thing is that
if you use === it won't use conversion during checking. it is strict comparing but if you use == then it will done conversion and then comapare with each other.
try like this
function forLoops(userInput) {
for (var x = 0; x < places.length; x++) {
if(userInput === places[x]) {
console.log("Your place input " + userInput + " is on our database.");
} else {
console.log("No place logged!");
}
}
}
pass user input to foorloop during calling

When using the === , you have to make sure that both operands are of the same type, in your case 'userInput' and all elements contained in your array 'places'. Try with == as suggested in the comments.

Related

token error when checking if a word exist with for loop and indexOf

I'm trying to check if there the word "#gmail.com" in the user input when the user type anything and if the word is not there, then repeat the question until the user includes the word "#gmail.com" but I'm getting token error in the console with unexpected ), I just started learning loops but wanted to try this idea with only for loops and if statements.
for (var userInput = prompt("enter your email"); userInput.indexOf("#gmail.com") === -1); {
var userInput = prompt("enter your email");
if (userInput.indexOf("#gmail.com") !== -1) {
alert("Welcome");
}
}
You're for-loop syntax is wrong. It has to have 3 statements in braces, like this:
for(var i = 0; i < 2; i++) {
//Do something
}
The first statement is excecuted once when the loop starts.
The second statement checks if the code inside the loop should be excecuted.
And the third statement gets excecuted after each loop.
So in your case it would be:
//We ignore the last statement, but have to keep the semicolon!
for (var userInput = prompt("enter your email"); userInput && userInput.indexOf("#gmail.com") === -1; ) {
userInput = prompt("enter your email");
if (userInput && userInput.indexOf("#gmail.com") !== -1) {
alert("Welcome");
}
}
This would be looping with a for-loop like you did, but of course Félix Brunets answer is more elegant for this purpose.
I hope this helps. -Minding
as I understood what you wanted to do :
var userInput;
do {
userInput = prompt("enter your email");
} while(userInput.indexOf("#gmail.com") === -1)
alert("Welcome");
It's may not be the best way to do it. With a script like that, you do not check where the "#gmail.com" is, you cannot stop or cancel, etc.

Javascript - Selecting an element in a list

How do I select an element from a list using Javascript. Here is some of my code:
var score = 0;
var bin = 0;
var question = -1;
var answers = ['higher', 'lower', 'higher', 'lower', 'higher'];
function answer_question(response) {
if (response == 1) {
if (answer[question] == "higher"){
score ++;
console.log(score);
} else {
bin ++;
console.log("Bin: ");
console.log(bin);
}
}
else if (response == 0) {
if (answer[question] == "lower") {
score ++;
console.log(score);
} else {
bin ++;
console.log("Bin: ");
console.log(bin);
}
}
}
However it doesn't work, I think this is due to the
answer[question] == "higher"
Thanks for your help!
This is because of three things:
answer is not defined. I suspect you meant answers. This could be just a typo.
Even if you did answers[question], well, question = -1, and answers[-1] returns undefined in Javascript. JS does not have the concept of negative indexing, so you can't use negative numbers as index subscripts. Use any number between 0 and answers.length - 1 instead, like so:
answers[0] // returns 0th (first) element of answers array
You never increment or change question. Every time you run this code, answers[question] always returns the same thing. In that case, why do you even have that line?
To answer your question as stated, however, array elements can be accessed by index like so: array[index]. index can be any integer between 0 and one less than the length of the array.

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.

Javascript for loop behaving as though 2=21

I've found a lot of discussion about javascript validation functions for forms but can't find anyone running into this particular problem.
In the code below, even though there are 21 values in the array 'fields[]', the for loop ends after 2 iterations. The last alert it pops reads "1 < 21" - it's as though it thinks 2 is not less than 21.
I thought it might be a data type error but can't figure it out. Thanks to anyone who can see it.
var fields = new Array;
var fields = [
document.forms["survey"]["Q1Age"].value,
document.forms["survey"]["Q2Gender"].value,
document.forms["survey"]["Q3Education"].value,
document.forms["survey"]["Q4Field"].value,
document.forms["survey"]["Q6Other"].value,
document.forms["survey"]["Q7Edited"].value,
document.forms["survey"]["UserAccount"].value,
document.forms["survey"]["Whole"].value,
document.forms["survey"]["Sections"].value,
document.forms["survey"]["Images"].value,
document.forms["survey"]["Keywords"].value,
document.forms["survey"]["writing"].value,
document.forms["survey"]["trustworthy"].value,
document.forms["survey"]["accuracy"].value,
document.forms["survey"]["bias"].value,
document.forms["survey"]["info"].value,
document.forms["survey"]["Viz1"].value,
document.forms["survey"]["Viz2"].value,
document.forms["survey"]["VizDescription"].value,
document.forms["survey"]["VizOver"].value,
document.forms["survey"]["submit2"].value
];
var err = 0;
//Start Validation Loop
for(var i = 0; i < fields.length; i++) {
alert(i + " < " + fields.length); //test how many iterations
//Check Fields in Array to Make Sure they are not Empty
if(fields[i].value == "" || fields[i].value == "Select One") {
err++;
}
}
if(err === 0) {
//Submit Form
//document.survey.submit();
return true;
} else {
//If there are errors, return false and alert the user
alert("Please fill out all of the fields.");
return false;
}
}
Since you are getting the input's value when you are creating the array your array elements are already strings, so in your if statement you are trying to get property value from a string, which is probably causing the script to end cause it is trying to access an undefined property
Your if statement should be this.
if(fields[i] == "" || fields[i] == "Select One") {
err++;
}

getting values and assigning them to a hidden field

I have the following function that is suppose to take a value from a field in a form and assign it to a hidden field when its called. for some reason its not working and I cant give you more details on why its not working simply because javascript doesnt really tell you much about whats wrong.
function clickChange(stype){
if(stype == '1'){
var fValue = document.getElementById('checkB1').value;
if(fCatValue == 0){
fCatValue = fValue;
}else{
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
}elseif(stype == '2'){
var sValue = document.getElementById('checkB2').value;
if(sCatValue == 0){
sCatValue = sValue;
}else{
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}
You need to convert the values to integer, or treat them as a string:
either:
var fValue = parseInt(document.getElementById('checkB1').value)
if(fCatValue == 0){....
or
var fValue = document.getElementById('checkB1').value;
if(fCatValue =='0'){...
Because of the placement of your declaration of the variable sCatValue it looks like sCatValue goes out of scope (or doesn't get declared at all).It would probably be easier on you if you declare all of your function scoped variables at the beginning of your function and cut down on the number of nested if statements.
I'd also recommend you use self explanatory variable names to cut down on confusing yourself. Also I'd recommend walking through your code with the use of a javascript debugger like firebug or ie 9's built in one. (surprising I know). And using jshint to help out with the common rules.
I found some other bugs and cleaned things up a bit and this is what I got
function clickChange(stype) {
//declared at the start so no scope undefined issues
var sValue = document.getElementById('checkB2').value;
var fValue = document.getElementById('checkB1').value;
//changed the comparision op from == to ===
//in javascript '===' throws false if the types compared are not the
//same otherwise it attemps to preform implicit casting for you
if (stype === '1') {
//parsing to insure that the types are matching
//the 10 is a radix param. It insures your number is formatted as a decimal
if (parseInt(fCatValue,10)=== 0) {
fCatValue = fValue;
} else {
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
} else if (stype === '2') {
if (parseInt(sCatValue,10)=== 0) {
sCatValue = sValue;
} else {
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}

Categories

Resources