gpt4 book ai didi

javascript - 检查多个或条件的更短方法

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:33 25 4
gpt4 key购买 nike

有没有更简单的方法来检查一个变量值与其他变量值的对比?目前我正在使用这样的代码:

if(a[i] == a[i-13] || a[i] == a[i+13] || a[i] == a[i-1] || a[i] == a[i+1]){
//my code
}

现在,有没有更短的方法来做到这一点?我知道我可以使用 switch ,但是我不得不多次编写我的函数。有更简单的方法吗?

最佳答案

你不需要用一个开关多次编写你的函数:

switch(a[i]){
case a[i-13]:
case a[i+13]:
case a[i-1]:
case a[i+1]:
// This code will run if any of the above cases are true.
}

然而,有趣的是,这几乎是相同数量的字符(取决于您如何格式化它)。 switch 语句通常不如显式 if 语句强大,但在这种情况下,我发现它更清晰且更不容易出错。

关于javascript - 检查多个或条件的更短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com