Javascript OR 运算符在 if 语句中不起作用 [英] Javascript OR operator not working in if statement

查看:41
本文介绍了Javascript OR 运算符在 if 语句中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一周中的某一天与我的声明中列出的任何一天相匹配,我试图让这个 Javascript 做一些事情,并将其限制在 17:00 到 19:00 之间,但 OR 运算符没有按我预期的那样工作,我是 JS 新手,我想知道我是否误解了这个运算符的使用.如果我只列出一周中某一天的值,而不是像我的示例中的 3,那么代码会按我希望的那样工作.

I'm trying to get this Javascript to do something if the day of the week matches any of the days listed in my statement, as well as restricting it to between 17:00 and 19:00 hours, but the OR operator is not working as I expected, I'm new to JS and I'm wondering if I'm misunderstanding the use of this operator. If I were to list a value for just one day of the week, instead of 3 like in my example, the code works as I'd hoped.

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

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

推荐答案

在这种情况下,您最好使用范围检查,因为您只需要针对三个或更多的两个比较 - 而且它的可维护性更好,只需更改一个值,如有必要.

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) {

正确的 OR 条件需要括号,因为 && 优先于 ||

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

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

这篇关于Javascript OR 运算符在 if 语句中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆