简体   繁体   English

有没有办法在JavaScript中做类似if(Variable == 1或Variable == 2或Variable == 3)的事情?

[英]is there a way to do something like if (Variable == 1 or Variable == 2 or Variable == 3) in javascript?

我对javascript有点陌生,我无法在google搜索中找到任何内容,我正在为某个程序编写程序,并且能够执行类似我所要求的操作: if (Variable == 1 or Variable == 2 or Variable == 3)对于我要在其中执行的操作将是一个更干净,更简单的解决方案。

Use this: 用这个:

if(variable==1||variable==2||variable==3){
  //do some stuff
}

basically its depend on requirment. 基本上,它取决于需求。 you can write this in some other more clear ways like 您可以用其他一些更清晰的方式来编写此代码,例如

if ((Variable == 1 && Variable == 2) || Variable == 3)

if first 2 condition must be true an third one is OR 如果前两个条件必须为真,第三个条件为OR

if (Variable == 1 && (Variable == 2 || Variable == 3))

if first condition must be true and second or third in one is true 如果第一个条件必须为真,第二个或第三个条件为真

The comments to your question make good points, but in case you have to test your variable within a large set of values, something like this will be better. 问题的注释很有意义,但是如果必须在大量值中测试变量,则类似的方法会更好。

 // Define an array of accepted values; var acceptedValues = [1,2,3,4,5,6,7,8,9,10]; // Test the variable. var variable = 11; if (acceptedValues.includes(variable)) console.log("variable has a valid value"); else console.log("variable does not have a valid value"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM