简体   繁体   English

编写此速记条件三元运算符以比较两个变量的正确方法是什么?

[英]What's the proper way to write this short hand conditional ternary operator to compare two variables?

I'm having trouble figuring out how to write a shorthand conditional statement. 我在弄清楚如何编写速记条件语句时遇到了麻烦。 Here's an example of the code: 这是代码示例:

const siteIdentifier = "bar";
const refOne = "foo";
const refTwo = "bar";

(siteIdentifier == refOne || refTwo) ? "primary" : "secondary";

I've also tried using .match and other variations but was unsuccessful with that as well. 我也尝试过使用.match和其他变体,但是也没有成功。

I'm looking to compare the siteIdentifier string to two possible strings. 我正在寻找将siteIdentifier字符串与两个可能的字符串进行比较。 If the strings match, we're returning "primary" . 如果字符串匹配,则返回"primary" If it doesn't match one of the two, it returns "secondary" . 如果不匹配两者之一,则返回"secondary"

one way would be 一种方法是

(siteIdentifier == refOne || siteIdentifier == refTwo) ? "primary" : "secondary";

... another one could be (more useful when you have many strings to match to) ...另一个可能是(当您有许多字符串要匹配时更有用)

~[refOne, refTwo].indexOf(siteIdentifier) ? "primary" : "secondary";

which is the same as 这与

[refOne, refTwo].indexOf(siteIdentifier) >= 0 ? "primary" : "secondary";

尝试这个 :

(siteIdentifier == refOne) ? "primary" : (siteIdentifier == refTwo ? "primary" : "secondary");

Just for the completeness, an object with all possibillities together. 为了完整起见,一个具有所有可能性的对象在一起。

const obj = { foo: 'primary', bar: 'primary', default: 'secondary'};
x = obj[siteIdentifier] || obj.default;

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

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