简体   繁体   English

或运算符不在 IF 语句 Node.js 中工作

[英]Or operator not working in IF statement Node.js

I originally had a route in node.js that stated this:我最初在 node.js 中有一条路由,说明了这一点:

If the req.url === something or something or something or something, do this, else, do that.如果 req.url === 某物或某物或某物或某物,则执行此操作,否则,执行此操作。

The problem is that the else statement never got executed even though the if condition was not met.问题是即使不满足 if 条件,else 语句也从未执行过。 Only the if statement executes no matter what无论如何都只执行 if 语句

I have broken down my route to bare minimum trying to figure out the problem.我已经将我的路线分解到最低限度,试图找出问题所在。 I simplified it to this:我将其简化为:

app.get('/test', function(req,res) {

        var category = 'stupid3';

        if(category === 'stupid' || 'stupid2') {

            res.end('yup');

        } else {

            res.end('nope');

        }

});

What am I doing wrong?我究竟做错了什么?

Why wont the else statement execute?为什么else语句不执行?

You're using it incorrectly.你使用它不正确。

category === 'stupid' || category === 'stupid2'

Your version is effectively...您的版本有效...

 (category === 'stupid') || 'stupid2'

...so because a non-empty string is "truthy", the RHS will always cause the || ...所以因为非空字符串是“真实的”,RHS 总是会导致|| to pass.通过。

the else statement is never executed because your if condition always returns true.. else 语句永远不会执行,因为您的 if 条件总是返回 true..

if (category === 'stupid' || 'stupid2') {

the second part of the condition ie after the ||条件的第二部分,即|| operator is 'stupid2 which is a truthy value运算符是'stupid2 ,这是一个真值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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