你能缩短'if'一个变量可以是多个变量的表述

Can you shorten an 'if' statement where a certain variable could be multiple things

本文关键字:变量 一个 if      更新时间:2023-09-26

因为我有时需要像

这样的if语句
if (variable == 'one' || variable == 'two' || variable == 'three') { 
    // code
}

我想知道你是否可以把这个写得更短一些,比如:

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

or…

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

任何一只猫都有很多剥皮的方法

~ is bitwise NOT…所以-1变成0 0变成-1 1变成-2等等

所以…

当indexOf为0或更大时,~与indexOf为"真",即找到值…

基本上是一个快捷方式,我可能不会在代码中使用它,因为超过一半的人会挠头想知道代码是做什么的:p

你可以试试:

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
}