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

发布于 2025-01-19 16:12:15 字数 239 浏览 5 评论 0原文

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

if (filteredMnth === 'mnth') {
         
  return (new Date(exp?.date).getMonth().toString() === "0" || "1" || "2" || "3" || "4" || "5" || "6"   )

}

How to simplify the code when using multiple or operators.
I have a list of numbers from 0 to 6 separated by logical or.Is there any way to simplify it?

if (filteredMnth === 'mnth') {
         
  return (new Date(exp?.date).getMonth().toString() === "0" || "1" || "2" || "3" || "4" || "5" || "6"   )

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幸福还没到 2025-01-26 16:12:15

对于这种具体情况,您可以执行 ->

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

For this specific case you can do ->

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

一场信仰旅途 2025-01-26 16:12:15

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

const validValues = [ 0, 1, 2 ];
const input = 2;

validValues.includes(input);
// => true

const input2 = 3;

validValues.includes(input2);
//=> false

As @罗比Cornelissen 已经在评论中提到,在你的情况下它确实没有任何意义,但我在此处包含此模式是为了回答你的问题的更通用版本。

A nice pattern for this, is to create an Array of valid or accepted values and use the Array.prototype.includes to check for one from the user input:

const validValues = [ 0, 1, 2 ];
const input = 2;

validValues.includes(input);
// => true

const input2 = 3;

validValues.includes(input2);
//=> false

As @Robby Cornelissen already mentioned in the comment, in your case it really does not make any sense, but I'm including this pattern here to answer a more generic version of your question.

上课铃就是安魂曲 2025-01-26 16:12:15

由于您有多个值,因此可以使用列表,并包含下面的方法

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

Since you are having multiple values you can make use of List and includes method as below

const validMonths = ["1", "2", ...]
const monthToCheck = new Date(exp?.date).getMonth().toString()
if(validMonths.includes(monthToCheck)){
    //Evaluates true if value exist
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文