你能缩短一个 'if' 语句,其中某个变量可能是多个东西吗
Can you shorten an 'if' statement where a certain variable could be multiple things
因为我有时需要像
这样的if语句
if (variable == 'one' || variable == 'two' || variable == 'three') {
// code
}
我想知道你是否可以把它写得更短一些,比如:
if (variable == ('one' || 'two' || 'three')) {
// code
}
你可以试试:
if(variable in {one:1, two:1, three:1})
或:
if(['one', 'two', 'three'].indexOf(variable) > -1)
或在 ES6 中(现在可以在大多数最新的浏览器中本地运行):
if(new Set(['one', 'two', 'three']).has(variable))
请注意,解决方案 2 将与数组的大小成线性比例,因此如果您要检查的值超过几个,这不是一个好主意。
不,这样的多重比较没有捷径可走。如果您尝试,它将计算表达式 ('one' || 'two' || 'three')
的值,然后将其与变量进行比较。
您可以将值放入数组中并查找它:
if ([ 'one', 'two', 'three' ].indexOf(variable) != -1) {
// code
}
您可以使用开关:
switch (variable) {
case 'one':
case 'two':
case 'three':
// code
}
您可以在对象属性中查找值(但对象值只是允许属性存在的虚拟值):
if (varible in { 'one': 1, 'two': 1, 'three': 1 }) {
// code
}
或..
if (~['one', 'two', 'three'].indexOf(variable))
任何有多种剥皮方法的猫
~
是 按位非 ... 所以 -1 变成 0,0 变成 -1,1 变成 -2 等等
所以 ... ~ with indexOf 是 "truthy" 当 indexOf 为 0 或更大时,即找到值 ...
基本上这是一个快捷方式,我可能不会在预期被其他人阅读的代码中使用,因为超过一半的人会挠头并想知道代码做了什么:p
因为我有时需要像
这样的if语句if (variable == 'one' || variable == 'two' || variable == 'three') {
// code
}
我想知道你是否可以把它写得更短一些,比如:
if (variable == ('one' || 'two' || 'three')) {
// code
}
你可以试试:
if(variable in {one:1, two:1, three:1})
或:
if(['one', 'two', 'three'].indexOf(variable) > -1)
或在 ES6 中(现在可以在大多数最新的浏览器中本地运行):
if(new Set(['one', 'two', 'three']).has(variable))
请注意,解决方案 2 将与数组的大小成线性比例,因此如果您要检查的值超过几个,这不是一个好主意。
不,这样的多重比较没有捷径可走。如果您尝试,它将计算表达式 ('one' || 'two' || 'three')
的值,然后将其与变量进行比较。
您可以将值放入数组中并查找它:
if ([ 'one', 'two', 'three' ].indexOf(variable) != -1) {
// code
}
您可以使用开关:
switch (variable) {
case 'one':
case 'two':
case 'three':
// code
}
您可以在对象属性中查找值(但对象值只是允许属性存在的虚拟值):
if (varible in { 'one': 1, 'two': 1, 'three': 1 }) {
// code
}
或..
if (~['one', 'two', 'three'].indexOf(variable))
任何有多种剥皮方法的猫
~
是 按位非 ... 所以 -1 变成 0,0 变成 -1,1 变成 -2 等等
所以 ... ~ with indexOf 是 "truthy" 当 indexOf 为 0 或更大时,即找到值 ...
基本上这是一个快捷方式,我可能不会在预期被其他人阅读的代码中使用,因为超过一半的人会挠头并想知道代码做了什么:p