您是否可以缩短某个变量可能是多个事物的"if"语句 [英] Can you shorten an 'if' statement where a certain variable could be multiple things

查看:70
本文介绍了您是否可以缩短某个变量可能是多个事物的"if"语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我有时需要if语句,如

Since I sometimes needs an if-statement like

if (variable == 'one' || variable == 'two' || variable == 'three') { 
    // code
}

我想知道您是否可以写得更短一些,例如:

I was wondering if you could write this any shorter, something like:

if (variable == ('one' || 'two' || 'three')) {
    // code
}

推荐答案

或..

if (~['one', 'two', 'three'].indexOf(variable))

任何有很多方法可以剥皮的猫

any cat with many ways to skin it

~按位非 ... ...因此-1变为0,0变为-1,1变为-2,依此类推

~ is bitwise NOT ... so -1 becomes 0, 0 becomes -1, 1 becomes -2 and so on

所以...当indexOf为0或更大时,即indexOf为真",即...的值...

so ... ~ with indexOf is "truthy" when indexOf is 0 or greater, i.e. value is found ...

基本上,这是一条捷径,我可能不会在预期会被其他人阅读的代码中使用,因为一半以上的人会挠头并想知道代码做了什么:p

basically it's a shortcut that I probably wouldn't use in code expected to be read by other people as over half would scratch their heads and wonder what the code did :p

这篇关于您是否可以缩短某个变量可能是多个事物的"if"语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆