简体   繁体   中英

Multiple conditions using an AND if Statement, javascript

Can anyone tell me what's wrong with this if statement?

If I use either of the two main conditions on their own the statement works fine but when I add that middle && statement , it stops working. I've searched online and can't see what's wrong.

PS . I can even change that middle && to a || statement and it works as well. I'm so confused.

if ((containerId.id == "LineOne" && dropLoc == "dropLocation1.1") && (containerId.id == "LineTwo" && dropLoc == "dropLocation2.2"))
        {
            alert("finished");
            cdpause();      
        }

I've searched online and can't see what's wrong.

I can even change that middle && to a || statement and it works as well

Because containerId.id can't be LineOne and LineTwo at the same time.

Similarly, dropLoc can't have two values at the same time.

But it can have one of the two values, so replace && with || .

   if ((containerId.id == "LineOne" && dropLoc == "dropLocation1.1") || 
       (containerId.id == "LineTwo" && dropLoc == "dropLocation2.2"))
   {
        alert("finished");
        cdpause();      
   }

You could combinte the two checks with an OR, because, you can not have two different values at the same time.

Beside that, you need no brackets, because of the operator precedence of logical AND && over logical OR || .

if (
    containerId.id == "LineOne" && dropLoc == "dropLocation1.1" ||
    containerId.id == "LineTwo" && dropLoc == "dropLocation2.2"
) {
    alert("finished");
    cdpause();      
}

就像萨特帕尔说的

 if(containerId.id == "LineOne" && dropLoc == "dropLocation1.1") || (containerId.id == "LineTwo" && dropLoc == "dropLocation2.2")

You already had the correct solution, you should have a || (or) instead of a && (and) in the middle.

It's basic boolean logic: you have two expressions with "and", and you want to execute your code if either of those expressions are true, so you join those expressions with "or".

"If the name is John and it's Monday OR if the name is Jane and it's Tuesday , then remind them to shop for groceries." => on Monday, it's John's turn to go shopping, on Tuesday, it is Jane's.

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