简体   繁体   中英

What is wrong with this if statement logic in JavaScript?

if(stringName.charAt(0) != 'Q' || stringName.charAt(0) != 'W' || stringName.charAt(0) != 'E'){

        SetID = "Yes";

    }

The above code when I use alert to popup the windows the value of My.String.charAt(0) is returning the correct value but I don't know why it goes inside the if statement and change the value of SetID to Yes

I'm trying to figure out what is wrong with it and really can't see anything

SetID is initialize to No

You're using || but you probably mean && ...

The way it is now, it'll always be true . "If the character is not 'Q', or it's not 'W', or it's not 'E', then..." — even if it is one of those characters, it will not be the others, so the expression evaluates to true .

Let's break down your statement.

MyString.charAt(0) != 'Q'

Okay, so if it's not Q then it continues.

||

So if the character is Q, continue along the chain.

MyString.charAt(0) != 'W'

By this point we've established that either the character is NOT Q (in which case SetID = "Yes" is run), or it is IS Q. But if it is Q, then clearly it is not W, therefore this next condition is true and SetID = "Yes" is run.

You see? No matter what the character is, it passes the test.

I think you meant to use && , not || . If you use && , then the SetID = "Yes" is only run if the character is NONE OF Q, W or E.

Not an answer [too much code for a comment], but another possible solution using a reg exp

var stringName = "Quick";
if( (/^[QWE]/).test(stringName) ){
   SetID = "Yes";
}

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