简体   繁体   中英

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

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"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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