检查是否x
变量等于 1 或 2,我通常会这样做:
if (x === 1 || x === 2){
// ....
}
但这在某些情况下可能会变得非常麻烦。
Edit :I'm working right now on this and writing the fonction name every time i think can be done in a cleaner manner:
if (
this.getNotificationStatus() === 'denied' ||
this.getNotificationStatus() === 'blocked'
)
还有其他更简单的方式来写这个吗?
谢谢
最佳答案
你可以这样做:
if ([1, 2].includes(x)) {
// ....
}
或者:
if ([1, 2].indexOf(x) > -1) {
// ....
}
或者:
switch (x) {
case 1:
case 2:
// ....
break;
default:
}
不过,我认为它们并不比您的解决方案“更轻”。
关于javascript - 如何在 JS 中以干净的方式检查变量是否等于两个值之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60001135/