否则 - 如果JavaScript中的语句似乎在Moment.js工作日中引起一些奇怪的行为

问题描述:

我正在使用Moment.JS来检查当前日不是星期日还是星期六。如果不是,那么做一些操作。否则 - 如果JavaScript中的语句似乎在Moment.js工作日中引起一些奇怪的行为

这里是我的代码:

let currentDay = moment().weekday(); 

if(currentDay !== 0 || currentDay !== 6){ 
    doSomeOperation(); 
    } else { console.log("we should get here on a Sunday"); } 

这对我来说,使完整意义上的 - 如果CURRENTDAY不是周日或周六然后doSomeOperation();(对于背景下,我在一个星期天运行此。)

然而,它会失败,并在if块中运行doSomeOperation();方法。我已经在所有可能的组合中运行了它,但仍然失败。然后我决定分开运行它们。

if(currentDay !== 0){ 
     doSomeOperation(); 
    } else { console.log('you should get here'); } 

成功 - 我得到else块。这没有意义 - 因为如果成功了,那么为什么上述失败?

我终于改变它送到这样的:

if ((currentDay === 0 || currentDay === 6)){ 
console.log('you should get here'); 
} else { doSomeOperation() } 

这种成功并打印出“你应该到这里来”。如果我颠倒了操作员,那么所有的检查都会通过。我的问题是我做错了什么?

您需要在条件中采用逻辑AND,因为您想排除这两天。

if (currentDay !== 0 && currentDay !== 6) { 
    // do some operations 
} 

否定条件,你可以申请De Morgan's laws

if (currentDay === 0 || currentDay === 6) { 
    // saturday or sunday 
} else { 
    // other days 
    // do some operations 
} 
+0

喜@Nina - 感谢您的回复。为什么当我颠倒操作员时,他们都与逻辑或操作? – xn139

+0

它不与等于或者一起工作,因为每个部分有时是“真”的,条件总是“真”。 –

+1

当我在if语句遇到问题时,我总是尝试将它们转换成问题以查看它们是否有意义。如果我不能,那么代码通常会有问题。或者代码太复杂,需要细分。 –