简体   繁体   English

JavaScript / Node.JS-使用OR运算符的紧凑方式?

[英]JavaScript/Node.JS - compact way of using OR operator?

Let's say I have a situation for checking a string. 假设我有一个检查字符串的情况。 I need to check if it matches a or matches b . 我需要检查它是否匹配a或匹配b Now, of course, I could just do 现在,我当然可以

var firstVar = "a"
var secondVar = "b"
var message = "atest" // note that I might not know what message is. it could be anything. it could be just "test" or just "a"
if ((message === firstVar + "test") || (message === secondVar + "test")) {
   console.log("success!")
}

but is there any way to compact this down? 但是有什么办法可以压缩下来吗? Something relating to having a myVar being an array with values of a and b and then checking if message starts with any value in myVar ? myVar是具有ab值的数组然后检查message是否以myVar任何值开头有关的东西 If anyone has a tip, that would be much appreciated. 如果有人给小费,不胜感激。 Thanks! 谢谢!

Using an array with some will be the simplest approach: 将数组与some将是最简单的方法:

var tests = ["a", "b"];
var message = "atest";
if (tests.some(function(t) { return message === t + "test"; })) {
    console.log("success!")
}

If you can use ES6 and need to run this check very often, it might make sense to use 如果您可以使用ES6并且需要经常运行此检查,那么使用它可能很有意义

const choices = new Set(["a", "b"].map(t => t + "test"));
…
var message = "atest";
if (choices.has(message)) {
    console.log("success!")
}

ES5: ES5:

 var vars = ["a", "b"].map(function(v) { return v + "test"; }); var message = "atest"; if (vars.indexOf(message) > -1) { console.log("success!"); } 

ES6: ES6:

 var vars = ["a", "b"].map(v => v + "test"); var message = "atest"; if (vars.includes(message)) { console.log("success!"); } 

I would probably use Array.prototype.some on the array of prefixes and then...: 我可能会在前缀数组上使用Array.prototype.some然后...:

  • If the prefixes are all single characters, just do messsage[0] === prefix , which should be the fastest option (no function calls and no string concatenation, just a simple and fast comparison operator. 如果前缀都是单个字符,则只需做messsage[0] === prefix ,这应该是最快的选择(没有函数调用也没有字符串连接,只是一个简单而快速的比较运算符。

     const prefixes = ["a", "b"]; const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; console.log(prefixes.some(prefix => message1[0] === prefix)); console.log(prefixes.some(prefix => message2[0] === prefix)); console.log(prefixes.some(prefix => message3[0] === prefix)); 

  • If the prefixes can have more than one character (also works for a single character), then I would do message.indexOf(prefix) === 0 : 如果前缀可以包含多个字符(也适用于单个字符),那么我将执行message.indexOf(prefix) === 0

     const prefixes = ["at", "bt"]; const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; console.log(prefixes.some(prefix => message1.indexOf(prefix) === 0)); console.log(prefixes.some(prefix => message2.indexOf(prefix) === 0)); console.log(prefixes.some(prefix => message3.indexOf(prefix) === 0)); 

You could also build and use a RegExp , which might be faster (depending on the amount and size of the prefixes) if you are going to execute the code multiple times (it will have a penalization the first time you build the RegExp from a string, but then you just reuse that one over and over): 您还可以构建和使用RegExp ,如果您打算多次执行代码,则速度可能更快(取决于前缀的数量和大小)(第一次从字符串构建RegExp时会受到惩罚) ,但是您可以反复使用该代码):

  • If the prefixes are a single character: 如果前缀是单个字符:

     const prefixes = ["a", "b"]; const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; const regexp = new RegExp(`^[${ prefixes.join('') }]`); console.log(regexp.test(message1)) console.log(regexp.test(message2)) console.log(regexp.test(message3)) 

  • If the prefixes are multiple characters (also works for a single character): 如果前缀是多个字符(也适用于单个字符):

     const prefixes = ["at", "bt"]; const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; const regexp = new RegExp(`^(${ prefixes.join('|') })`); console.log(regexp.test(message1)) console.log(regexp.test(message2)) console.log(regexp.test(message3)) 

If you want to check that message is actually a combination of any of those prefixes plus something else, let's say "test" in your example, then you may want to precompute all the possible options: 如果要检查message是否实际上是这些前缀中的任何一个加上其他内容的组合,在示例中说"test" ,则可能需要预先计算所有可能的选项:

  • With an Array (or Set as @Bergi suggested) and Array.prototype.includes or Array.prototype.indexOf 使用Array(或建议设置为@Bergi)和Array.prototype.includesArray.prototype.indexOf

     const prefixes = ["a", "b"]; const word = "test"; const options = prefixes.map(prefix => `${ prefix }${ word }`); const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; console.log(options.includes(message1)); console.log(options.includes(message2)); console.log(options.includes(message3)); console.log(options.indexOf(message1) !== -1); console.log(options.indexOf(message2) !== -1); console.log(options.indexOf(message3) !== -1); 

  • With a RegExp and RegExp.prototype.test or String.prototype.match : 使用RegExp和RegExp.prototype.testString.prototype.match

     const prefixes = ["a", "b"]; const word = "test"; const regexp = new RegExp(`^(${ prefixes.join("|") })${ word }`); const message1 = "atest"; const message2 = "btest"; const message3 = "ctest"; console.log(regexp.test(message1)); console.log(regexp.test(message2)); console.log(regexp.test(message3)); console.log(!!message1.match(regexp)); console.log(!!message2.match(regexp)); console.log(!!message3.match(regexp)); 

Use includes ; 用途includes ; based on your edit: 根据您的修改:

const allowed = ['a','b','ccc'];

if( allowed.includes(`${ message }test`) ) {
    console.log("success!")
}

Example of using includes and vanilla 使用include和vanilla的示例

ES6 way ES6方式

const testArray = [1,2,3];

testArray.includes(1); //returns true
testArray.includes(24); //returns false

ES5 way ES5方式

var testArray = [1,2,3];
testArray.indexOf(1) // returns 1 since its a member.
testArray.indexOf(43) //returns -1 since it's not a member.

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

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