在JavaScript(以及大多数其他编程语言)中,我已经注意到,在检查同一变量的多个coniditions并针对每个条件执行相同操作时,很难编写if-stats。在像这样的场景中,可以更简洁地编写if语句吗?更简洁地编写if语句
if(x==1|x==2|x==3){ //Is there any way to make this less verbose?
console.log("X equals either 1 or 2 or 3!");
}
//this isn't syntactically correct, but it's more concise,
//and I wish it were possible to write it more like this
if(x==(1|2|3)){
console.log("X equals either 1 or 2 or 3!");
}
这似乎是你的问题被用来作为一个精神的挑战,提供各种精心设计的答案。但我怀疑真正的答案是“不”。 – simon
@simon不,我实际上想要找到一种方式来编写if语句,这样我就不需要编写大量冗余代码了。)使用正则表达式(如下面的答案中所示)将是一个解。 –