Javascript OR运算符无法在if语句中使用 [英] Javascript OR operator not working in if statement

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

问题描述

如果一周中的某天与我的语句中列出的任何一天匹配,并且试图将其限制在17:00至19:00之间,我试图让此Javascript执行某项操作,但是使用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) {

由于||

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

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

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