我正在检查一个变量,例如foo,与多个值的相等性.例如,
if( foo == 1 || foo == 3 || foo == 12 ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
关键是这个繁琐的任务代码相当多.我想出了以下内容:
if( foo in {1: 1, 3: 1, 12: 1} ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但这并不完全吸引我,因为我必须为对象中的项目提供冗余值.
有没有人知道对多个值进行相等检查的正确方法?
什么是将一个值与多个选项进行比较的最漂亮的方法?
我知道有很多方法可以做到这一点,但我正在寻找最好的方法.
我问,因为我希望这是可行的(当你看它时,它显然不是这样):
if (foobar == (foo||bar) ) {
//do something
}
Run Code Online (Sandbox Code Playgroud) if (Progress.bar.status == 'finished' || Progress.bar.status == 'uploading'){
//code here
}
Run Code Online (Sandbox Code Playgroud)
我该如何缩短这个?我想写它而不必重复Progress.bar.status两次.
有点像:
Progress.bar.status == ('finished' or 'uploading').
Run Code Online (Sandbox Code Playgroud) 现在我有:
if (breadCrumbArr[x] !== 'NEBC' && breadCrumbArr[x] !== 'station:|slot:' && breadCrumbArr[x] !== 'slot:' && breadCrumbArr[x] !== 'believe') {
// more code
}
Run Code Online (Sandbox Code Playgroud)
但我认为这可以做得更好......
在一个JS库中,我看到了这样的语法:
if (val > 5 == t) { ... }
Run Code Online (Sandbox Code Playgroud)
我在控制台测试了这个:
1 == 1 == 2 // false
2 > 1 == 1 // true
1 == 2 == 1 // false
1 == 1 == 1 // true
1 < 2 < 3 // true
1 > 2 > 3 // false
Run Code Online (Sandbox Code Playgroud)
乍一看都是正确的.这可以用吗?