简体   繁体   中英

Simple if-else statement always returns true

I am trying to make a simple if-else statement, but when I run the code, it always returns true , even if I enter something in the prompt that I know should be false . I have ran it through JsFiddle , and it seems that the code snippet is perfectly valid.

var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');

if ('captchaTest + captchaInput = 10') {
    alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
    alert('Failed, try again.'); window.location.href = 'main.html';
}

Can someone tell me what I did wrong?

Non-empty strings in JavaScript are truthy . 'captchaTest + captchaInput = 10' , when evaluated as Boolean, is true .

You need to remove the quotation marks and change = to == :

if (captchaTest + captchaInput == 10)

Apart from the answer that other provided I would also make a point that as per your captcha question, your condition should be like this

if (captchaInput == 10){
  alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
  alert('Failed, try again.'); window.location.href = 'main.html';
}

I don't see any use of the variable captchaTest

You shouldn't be using a 'captchaTest + captchaInput = 10' as it is a String and always evaluates to true unless it is an empty one.

Also you should use comparison operator == instead of assignment operator =

So remove the quotes

if ((captchaTest + captchaInput) == 10)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM