[英]javascript operators using AND and OR in conditional statements
I'm trying to display a message if only the conditional statements meet a certain requirement but with what I'm getting it fails me.如果只有条件语句满足特定要求,我试图显示一条消息,但我得到的结果让我失败了。 Currently, the script is like this
目前,脚本是这样的
if ((err.status === 401 && !request.url.includes("users") || !request.url.includes("friends")) ) {
console.log('hello')
}
What I want to achieve is when the status is 401
and the URL doesn't include either users
or friends
the console
should log hello
but it fails to work我想要实现的是当状态为
401
并且 URL 不包括users
或friends
时, console
应该记录hello
但它无法工作
when I change the code to this当我将代码更改为此
if ((err.status === 401 && !request.url.includes("users")) ) {
console.log('hello')
}
or this或这个
if ((err.status === 401 && !request.url.includes("friends")) ) {
console.log('hello')
}
it works, but I want it to check for both conditions它有效,但我希望它检查这两个条件
Just swap the ||
只需交换
||
for a &&
对于一个
&&
if (err.status === 401 && !request.url.includes("users") && !request.url.includes("friends")) {
console.log('hello')
}
If you think it through in your head it would sound like the following.如果你在脑海中仔细想想,听起来会像下面这样。
status
has to be 401
status
必须是401
url
should NOT include users
url
不应包括users
url
should NOT include friends
url
不应该包括friends
If you want to code it like you wrote it:如果你想像你写的那样编码:
status
has to be 401
status
必须是401
url
should NOT include users
OR friends
url
不应包括users
或friends
You could still do that, but just a little different:你仍然可以这样做,但有点不同:
if (err.status === 401 && !(request.url.includes("users") || request.url.includes("friends"))) {
console.log('hello')
}
Both these codes mean exactly the same, just write it how you prefer it more.这两个代码的意思完全一样,只是写你更喜欢它。 But always write it like it flows in your head.
但总是像它在你脑海中流动一样写下来。 Just type out what you think:)
只需输入您的想法:)
For string validations I suggest you to use Regular Expressions (It can allow more complex validations)对于字符串验证,我建议您使用正则表达式(它可以允许更复杂的验证)
if(error.status === 401 && !/users|friends/.test(request.url)){
console.log("hello")
}
The way that is parallel to the wording:平行于写法的方式:
if(err.status==401 && !(request.url.includes("users") || request.url.includes("friends")))
Visually:视觉上:
if
(
err.status==401
&&
!
(
request.url.includes("users")
||
request.url.includes("friends")
)
)
your code is almost ok, just some issue with brackets () .您的代码几乎没问题,只是括号()有一些问题。
the format is:格式是:
if( cond1 && !( cond2 || cond3 ) ) {
----- your logic ------
}
so your example should be like:所以你的例子应该是这样的:
if ( err.status === 401 && !( request.url.includes("users") || request.url.includes("friends") ) ) {
console.log('hello')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.