You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何if语句中的日期比较逻辑判断失效?

日期判断逻辑错误分析

我想要判断wh对象的日期不是周六或周日,因此编写了以下代码:

this.state.workingHours.map((wh) => {
      if (wh.date.getDay() !== 6 || wh.date.getDay() !== 0) {
        console.log(
          "goes in",
          this.context.dateService.format(wh.date, "EEEE")
        );
      }
    });

但控制台输出显示周六、周日也被纳入了判断范围:

goes in Wednesday
goes in Thursday
goes in Friday
goes in Saturday
goes in Sunday
goes in Monday
...

问题原因

你的逻辑运算符用错了。||是“或”运算,只要其中一个条件成立,整个表达式就为true:

  • 当日期是周六(getDay()返回6)时,wh.date.getDay() !== 0是成立的,所以整个条件为true,会进入代码块;
  • 当日期是周日(getDay()返回0)时,wh.date.getDay() !== 6是成立的,所以整个条件也为true,同样会进入代码块。

你需要的是“既不是周六,也不是周日”,也就是两个条件必须同时成立,这时候应该用“与”运算符&&。

修正后的代码

this.state.workingHours.map((wh) => {
      if (wh.date.getDay() !== 6 && wh.date.getDay() !== 0) {
        console.log(
          "goes in",
          this.context.dateService.format(wh.date, "EEEE")
        );
      }
    });

也可以换一种更直观的写法,用数组包含判断:

this.state.workingHours.map((wh) => {
      const day = wh.date.getDay();
      if (![0, 6].includes(day)) {
        console.log(
          "goes in",
          this.context.dateService.format(wh.date, "EEEE")
        );
      }
    });

内容的提问来源于stack exchange,提问作者der papa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 04:53:09