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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33089632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:06:31  来源:igfitidea点击:

Or operator not working in IF statement Node.js

javascriptnode.js

提问by Wee Wee

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. Only the if statement executes no matter what

问题是即使不满足 if 条件,else 语句也从未执行过。无论如何都只执行 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语句不执行?

回答by

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 ||to pass.

...所以因为非空字符串是“真实的”,RHS 将始终导致||通过。

回答by dpkg

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 i.e. after the ||operator is 'stupid2which is a truthy value

条件的第二部分,即||操作符后面的是'stupid2哪个是真值