admin管理员组

文章数量:1418085

the result I want is second if else statement if code not in the list then alert, I don't get why the first if else statement fail, I thought that just reverse second if else statement ?? do I misunderstand some thing??

/

var code = '500';

    if (code != '400' || code != '401' || code != '500') {
    	console.log('true');  // I don't want it alert here
    }
    
    
    if (code == '400' || code == '401' || code == '500') {	
      // I have to always leave this empty line  ...
    } else {
    console.log('second true');
    }

the result I want is second if else statement if code not in the list then alert, I don't get why the first if else statement fail, I thought that just reverse second if else statement ?? do I misunderstand some thing??

https://jsfiddle/e6qohvhc/

var code = '500';

    if (code != '400' || code != '401' || code != '500') {
    	console.log('true');  // I don't want it alert here
    }
    
    
    if (code == '400' || code == '401' || code == '500') {	
      // I have to always leave this empty line  ...
    } else {
    console.log('second true');
    }

Share Improve this question asked Mar 27, 2016 at 8:18 user1575921user1575921 1,0881 gold badge18 silver badges29 bronze badges 1
  • 1 I'm not sure to understand your question, but boolean !(a||b) is !a&&!b – SR_ Commented Mar 27, 2016 at 8:23
Add a ment  | 

4 Answers 4

Reset to default 4

This has to do with De Morgan's laws:

If you want to invert a statement you have to invert every operator.

!a bees a, b bees !b, ||bees &&, && bees ||.

So the inversion of your second if would be something like

(code != '400' && code != '401' && code != '500')

You may need to review the Morgan's laws.

Basically, if you want to negate (a || b || c) you need to use (!a && !b && !c)

Hope it helps,

if(code != '400' || code != '401' || code != '500'){}

always will be true because a variable cant be equal to multiple values

The problem is || First if statement for 500 is always true, that's why you are having problem/ Do it in this way and it should work the way you wanted it (check it out in your fiddle);

var code = 500;
alert(code);
console.log(code);
if (((code !== 400) || (code !== 401)) && (code !== 500)) {
    console.log('true');
  alert("123");
}

else if ((code == 400) || (code == 401) || (code == 500)) {
    alert("456");
} else {
console.log("second true");
alert("else");
}

本文标签: javascriptif else statement reverseStack Overflow