如何使用具有多个值的逻辑或运算符



如何在使用多个或运算符时简化代码。我有一个用逻辑或分隔的从0到6的数字列表。有什么方法可以简化它吗?

if (filteredMnth === 'mnth') {

return (new Date(exp?.date).getMonth().toString() === "0" || "1" || "2" || "3" || "4" || "5" || "6"   )
}

对于这种特定情况,您可以执行->

if (filteredMnth === 'mnth') {
return new Date(exp?.date).getMonth() <= 6;
}

一个很好的模式是创建一个validaccepted值的数组,并使用Array.prototype.includes从用户输入中检查一个:

const validValues = [ 0, 1, 2 ];
const input = 2;
validValues.includes(input);
// => true
const input2 = 3;
validValues.includes(input2);
//=> false

正如@Robby Cornelissen在评论中已经提到的那样,在你的情况下,这真的没有任何意义,但我在这里加入这个模式是为了回答你问题的一个更通用的版本。

由于您有多个值,您可以使用List和includes方法,如下所示

const validMonths = ["1", "2", ...]
const monthToCheck = new Date(exp?.date).getMonth().toString()
if(validMonths.includes(monthToCheck)){
//Evaluates true if value exist
}

最新更新