简体   繁体   中英

multiple conditions in an if - else in javascript

I'm trying to make a program that only accepts a few values. So, if "e" variable is not 1 or 2 or 3, says that the number is not correct, but if the value is equal to those numbers, then the else part is run.

All of this may sound very begginer level and easy to implement, and it is, but I ran the code and EVERY vaule I set to "e" runs the if part.

Here is code:

var e;

e=parseFloat(prompt("Input e",""));

 if(e!=1 || e!=2 || e!=3)
  {
  alert("put again E");
  }

 else
  {
  //whatever
  }

In English you said "not 1 or 2 or 3", but that is written as !(e == 1 || e == 2 || e == 3) ; or, you could go with the logically equivalent "not 1, and not 2, and not 3", expressed as e != 1 && e != 2 && e != 3 .

What you wrote is "not 1 or not 2 or not 3". If the value is 1, then it is not 2 (and also not 3), so "not 1 or not 2 or not 3" is still true. In fact, it is true for any value, because at least two of those (if not all three) will be true.

Since e can't have the value of 1,2 and 3 simultaneously, your condition is always going to evaluate to true. your version reads

if the value is different from 1 or different from 2 or different from 3 then do this.

So you will need to change it to something that reads more like

if the value is not either 1 or 2 or 3 then

if(!(e == 1 || e == 2 || e == 3)){...}

or you could do

if(e != 1 && e != 2 && e != 3){...}

which would read

if the value isn't 1 and isn't 2 and isn't 3

The result of those two options would be the same.

It's because || means or.

if(e!=1 || e!=2 || e!=3)

If you input e = 1 you will have

if(false OR true OR true)

which of course, evaluates to true.

You want &&, which means and, resulting in:

if(e!=1 && e!=2 && e!=3)

if you want to maintain your code structure. Or you could take the advice of the others, and put your "else" code into the "if" block and use ==.

You should use == rather than != like:

 if(e==1 || e==2 || e==3)//then re enter value

With your if, you mean if e is neither of 1,2,3 then ask user to reenter the value.

The reason is simple. If for example you input the value 1 the first part of your condition returns false , but the other 2 parts return true , then the condition can be read like this:

if( false || true || true ) {
 ...
}

So no matter what input, there will always be 2 true values against a false value. To get what you want, use && instead of || .

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