Javascript OR operator not working in if statement

依然范特西╮ 提交于 2019-12-01 20:42:44

In this case, you better use a range check, because you need only two comparisons against of three or more - and it is better maintanable, just to change a value, if necessary.

if (dayOfWeek >= 4 && dayOfWeek <= 6 && hour >= 17 && hour < 19) {

The right OR conditions needs parenthesis, because of the precedence of && over ||

if ((dayOfWeek == 4 || dayOfWeek == 5 || dayOfWeek == 6) && hour >= 17 && hour < 19 ) {

Just for the sake of posting another possibility, if you ever will have a dynamic input you may want to use an array and use indexOf to check whether the day exists in the list:

var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( [4,5,6].indexOf(dayOfWeek) > -1 && hour >= 17 && hour < 19 ){
    // do stuff
  } else {
    // do other stuff 
}

https://jsfiddle.net/hnzzfnot/1/

You need to use dayOfWeek but you can also limit the amount of checks you need to do....

var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( (dayOfWeek >= 4 && dayOfWeek <= 6) && (hour>=17 && hour < 19))
{
  // do stuff
}
else
{
  // doo other stuff
}

var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( (dayOfWeek == 4 || dayOfWeek == 5 || dayOfWeek == 6) && (hour >= 17 && hour < 19) ){
    // do stuff
    console.log("true");
  } else {
    // do other stuff 
    console.log("false");
}

Your if condition should be:

if ( (dayOfWeek == 4 || dayOfWeek == 5 || dayOfWeek == 6) && hour >= 17 && hour < 19 ){
    // do stuff
  } else {
    // do other stuff 
} 

Correct it like this,

var d = new Date();
var dayOfWeek = d.getDay(); // 0 = Sunday
var hour = d.getHours();

if ( (dayOfWeek == 4 || 5 || 6) && (hour >= 17 && hour < 19) ){
    console.log("if")
  } else {
    console.log("else")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!