繁体   English   中英

Javascript:缩短if(...或...)条件

[英]Javascript: Shorter a if ( … or …) condition

if (args.join(" ").toLowerCase() === "are you" || args.join(" ").toLowerCase() === "are you doing")

正如你所看到的,我使用两个非常相似的线条或一个案例。 有没有更短的方法来做到这一点?

["are you", "are you doing"].includes(args.join(" ").toLowerCase())

这个解决方案的好处是args.join(" ").toLowerCase()只执行一次,并且它非冗长,同时仍然具有表现力且易于理解。
它也很容易扩展。 如果您想要验证更多字符串,只需将这些字符串添加到数组中即可。

您可以使用Array.some()来重写复杂的OR条件。

它允许您添加任意数量的检查值,而不会重复太多。

 if (['are you', 'are you doing'].some(i => i === 'are you doing')) { console.log('passes') } if (['are you', 'are you doing'].some(i => i === 'are you')) { console.log('passes') } 

在以下if定义的可读性较低的var lc

if ((lc = args.join(" ").toLowerCase()) === "are you" || lc === "are you doing"){

}

由于你的值相似/相关并且是字符串,我会使用正则表达式

 function test(...args){ return /are you( doing)?/.test(args.join(" ")) } console.log(test("are", "you", "doing")) console.log(test("are", "you")) console.log(test("are", "yo")) 

只需事先加入连接和套管:

let lc = args.join(" ").toLowerCase();
if(lc === "are you" || lc === "are you doing"){

}

您可以使用变量say, text来保存小写值并缩短代码,还可以减少join()操作只执行一次。

var text = args.join(" ").toLowerCase();
if (text === "are you" || text === "are you doing"){
  ...
}

而看着它好像代码are you的就是你需要在最高级别的检查,所以你也可以使用indexOf()来检查文本值只有像

var text = args.join(" ").toLowerCase();
if (text.indexOf("are you") !== -1){
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM