comparing array position to prompt (javascript) - javascript

I'm trying to compare the input from a prompt window to the position of the correct answer in an array within an array.
This function logs the question and possible answers to the console. It then logs the correct answer, but does not recognize the input as correct ie. it will always show the else statement.
Code:
questionArray[randomQ].questionPrompt();
var currentQ = randomQ;
Question.prototype.answerPrompt = function(){
var tryQ = prompt("Enter number of the correct answer.");
if (currentQ === tryQ){
console.log('The correct answer is ' + this.answer)
} else {
console.log('Try again. ' + this.answer)
}
};
Console log. The final line comes after input of 0:
Question?
0) answer 0 - correct answer
1) answer 1
2) answer 2
Try again. 0
If I use
if (questionArray.answerArray[currentQ] === tryQ)
then the correct array item is found, and listed as undefined in a TypeError. How do I use that array item to compare to the prompt answer?

prompt will always return a string, so it won't be === to a number. Cast the prompt result to a number first.
You also probably want to exclude the empty string from defaulting to 0.
const guess = prompt("Enter number of the correct answer.");
const tryQ = guess && Number(guess);

Related

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

if statement not working when i try to use it in my code to check a variable

i am trying to detect what the variable is but it is not working
var question = prompt("press 1 for hi logged in console and press anything else for goodbye logged in console")
if (question ===1
) {
console.log("hi")
}else{
console.log("goodbye")
}
That's how == and === are different. You compare by === and it compares both value and type. prompt always returns string and '1' is not same as 1. So you either need to use == or compare as question === '1'.
prompt returns a string, you care compare the return value question to the value 1 as string as follows:
var question = prompt("press 1 for hi logged in console and press anything else for goodbye logged in console")
if (question === "1"
) {
console.log("hi")
}else{
console.log("goodbye")
}

Javascript: Ensure Input is Numbers Only

I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.

Returning undefined while calling same function

Here is my code
function secondval_prompt(firstval) {
var secondval = prompt("should be greater than 1st value");
if((secondval > firstval) && (secondval != "") && (!isNaN(secondval))) {
return secondval;
} else {
secondval_prompt(firstval);
}
}
var firstvalue = prompt("Enter 1st value");
var secondvalue = secondval_prompt(firstvalue);
alert(secondvalue);
If I gave the second value greater that first value on first time its returning the second value correctly.Once I gave the second value as wrong (less than first value) on first time and gave the correct value(greater than first value) on second time it return undefined...
Why its returning undefined on second attempt..
Demo link : http://jsbin.com/balufete/1/edit?js,output
Please try like this
First
Give first value as 100 &
Give Second value as 101
It will return 101
Second
Give first value as 100 &
Give Second value as 10 &
Again give Second value as 101
It will return undefined
You need to return the value from the recursive function as well.
return secondval_prompt(firstval);
Note that you are currently doing a comparison on the text values entered in the prompt. "5" will be considered higher than "10" due to their respective alphabetical order. You may want to parseInt the two inputs:
if(parseInt(secondval, 10) > parseInt(firstval, 10))
You should also apply firstval the same validity tests that you're currently applying to secondval. At the moment, your code will accept non-number values for firstval.

ignoring empty strings when looping through an array in JavaScript

I am attempting to go through an array and add up all the numbers. I used console.log to show me what values the script was using as shown below. I keep trying different variations of things in the if() but nothing seems to be working properly.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(score, total) {
if(score === " ") {
billycount += 1;
}
return +total + +score;
});
console.log(billycount); //0
console.log(billyTotalScore); //30
console.log(billyScoreList); // ["12", " ", "18"]
console.log(billyAverageScore) //10
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
The answer to billyAverageScore should equal 15 (30/2).
I tried if(score === "0") which gives me the same answers as above and if (score !== true) which gives me a count of 2 and an average of 30. I think reduce() is treating the empty string as a 0. I want to be able to count all the empty strings so I can discount them from the length when finding the average.
I have been wrestling this forever and feel like I'm missing one key concept behind it. Any help would be great! Thanks!
UPDATE:
For anyone who stumbles across this, here is the code I got to work.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(total, score) {
if (score === " " || total === " ") {
billycount++;
}
return +total + +score;
});
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
When I was just checking if (score === " ") I was forgetting that score will never be equal to the first term in the array. I just added || total === " ". the only time this would break down would be if the first element was " " and the second element was 0. I would want to billycount++ for the first element but not for the second. I'll have to give that some more thought.
The callback function of reduce should be function(total, score) instead of function(score, total).
see MDN:
previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.

Categories

Resources