[英]Use variables with OR to check true/false for another variable
I developed an algorithm that checks nextDay, nextMonth and nextYear (considers leap-year), with a boundary defined called weekSpan, that if it falls within it (and at a specific time defined elsewhere)... it'll perform an action . 我开发了一种算法,可以检查nextDay,nextMonth和nextYear(考虑leap年),并定义一个称为weekSpan的边界,如果该边界落入其中(并在其他地方定义的特定时间),它将执行一个操作。 It's working right now, but I'm concerned, because my weekSpan variable is defined with OR values (eg weekSpan = 1 || 2 || 3;).
它现在正在工作,但是我很担心,因为我的weekSpan变量是用OR值定义的(例如,weekSpan = 1 || 2 || 3;)。
Considering that there's a variable called weekDay (value between 0 and 6) and I want to check if that weekDay falls within the weekSpan... I did something like this: 考虑到有一个名为weekDay的变量(值在0到6之间),我想检查那个weekDay是否在weekSpan内...我做了这样的事情:
if (weekDay == weekSpan) {
(code here)...
}
But... I tried to recreate the condition by doing something like this in Chrome's V8: 但是...我试图通过在Chrome V8中执行以下操作来重新创建条件:
var weekSpan = 1 || 2 || 3 || 4 || 5;
var weekDay = 5;
if (weekDay == weekSpan) {
console.log("Woooohhhh!");
}
Result: undefined.
I'm not sure which is the right way to check true or false with my code or simply do: 我不确定哪种正确的方法可以通过我的代码检查真假,或者只是这样做:
if (weekSpan) {
(code here)...
}
Any ideas? 有任何想法吗?
You could use a function with an array for the values and check against. 您可以将带有数组的函数用于值并进行检查。
const isInWeekSpan = v => [1, 2, 3, 4, 5].includes(v); console.log(isInWeekSpan(3)); console.log(isInWeekSpan(0));
The pattern 模式
x = 1 || 2
returns the first truthy value 1 in combination with logical OR ||
返回第一个真实值1与逻辑OR
||
组合 . 。 This is not an apropriate method to check a value.
这不是检查值的合适方法。
That's not how ||
那不是
||
works. 作品。 Try setting weekSpan to an array of possible numbers, and then checking if weekDay is in that array.
尝试将weekSpan设置为可能的数字数组,然后检查weekDay是否在该数组中。
var weekSpan = [1, 2, 3, 4, 5]; var weekDay = 5; if (weekSpan.includes(weekDay)) { console.log("Woooohhh!"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.