在将m变量添加到if条件之前,以下函数有效。但是,我注意到一个错误,当时间从上午11点到下午12点时,if else没有运行noonTime
变量。我查看了我的代码并认为它与条件中没有指定的分钟有关。最初我的代码就像这样:var noonTime = (h >= 12 && h <= 17) ? true : false;
。然后我将其更改为:var noonTime = (h >= 12, m > 0 && h <= 17, m == 0) ? true : false;
尝试检查条件中的分钟数。
有没有人看到我在尝试检查条件下的分钟时出错了什么?
var customerName = 'Bob';
function timeNow() {
var d = new Date(),
h = ('0' + d.getHours()).slice(-2),
m = ('0' + d.getMinutes()).slice(-2);
// Checking time range
var morningTime = (h >= 5 && h <= 12, m == 0) ? true : false;
var noonTime = (h >= 12, m > 0 && h <= 17, m == 0) ? true : false;
var nightTime = (h >= 17 && h <= 5) ? true : false;
var greeting = "";
if (morningTime) {
greeting = "Good Morning";
} else if (noonTime) {
greeting = "Good Afternoon";
} else if (nightTime) {
greeting = "Good Evening";
}
return greeting;
}
// var helloTime = timeNow();
document.getElementById('dashboard-hello').innerHTML = timeNow() + ', ' + customerName + '!';
//$('#dashboard-hello').html(helloTime + ', ' + customerName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dashboard-hello"></div>
答案 0 :(得分:1)
您希望将小时和分钟比较结合起来。使用括号进行这些分组可以更容易阅读。然后你只需使用你想要的范围。
function getGreeting(d) {
h = d.getHours(), // There's no reason to format these as
m = d.getMinutes(); // strings, since you're comparing to numbers
// Checking time range
var morningTime = ((h >= 5 && h < 12) || (h === 12 && m == 0));
var noonTime = ((h === 12 && m > 0) || (h > 12 && h < 17) || (h === 17 && m === 0));
var nightTime = (h >= 17 || h <= 5)
var greeting = "";
if (morningTime) {
greeting = "Good Morning";
} else if (noonTime) {
greeting = "Good Afternoon";
} else if (nightTime) {
greeting = "Good Evening";
}
return greeting;
}
console.log("now: " + getGreeting(new Date()));
console.log("5 am: " + getGreeting(new Date(1, 1, 1, 5, 0, 0)));
console.log("12:00pm: " + getGreeting(new Date(1, 1, 1, 12, 0, 0)));
console.log("12:01pm: " + getGreeting(new Date(1, 1, 1, 12, 1, 0)));
console.log("5:00pm: " + getGreeting(new Date(1, 1, 1, 17, 0, 0)));
console.log("5:01pm: " + getGreeting(new Date(1, 1, 1, 17, 1, 0)));
console.log("12:00am: " + getGreeting(new Date(1, 1, 1, 0, 0, 0)));
&#13;
我已将日期作为测试目的函数的参数。要返回它,只需删除d
并将第一行代码放回原位。
答案 1 :(得分:-1)
逗号运算符将评估每个操作数,但仅返回最后一个操作数的值。在这种情况下,您可能最好使用更多的AND / OR运算符来更好地评估您尝试做的事情。
我实际上并不完全确定你想要做什么,但也许你想要:
var morningTime = ((h >= 5 && h <= 12) && m == 0) ? true : false;
var noonTime = ((h >= 12 && m > 0) && (h <= 17 && m == 0)) ? true : false;
但也许你可以简化整个代码段,就像这样......
if (h > 5 && h <= 12) {
return "Good Morning";
}
else if (h > 12 && h <= 17)
return "Good Afternoon";
}
else if (h > 17 && h <= 5)
return "Good Evening";
}