使用三元 if...else 运算符时出错

Error when using Ternary if...else operator

我正尝试开始在我的代码中使用 shorthand javascript,但我还不是很熟练。我试图将我的 if...else 语句转换为 ternary if...else。我尝试时遇到错误。

Javascript:

if (x.includes(name)) {
  metric_val = funcOne(a);
} else if (y.includes(name)) {
  metric_val = funcTwo(a);
}

三元 if...else

let metric_val = (x.includes(name)) ? funcOne(a) : (y.includes(name)) ? funcTwo(a);

错误:

Uncaught SyntaxError: Unexpected token ;

我做错了什么?

:后面不能有其他的?,所以正确的做法是正确使用括号

metric_val = x.includes(name) ? funcOne(a) : (y.includes(name) ? funcTwo(a) : null);

如果两者都是false

就会有null

当两个条件都不匹配时,您的 if/else if 不会分配给 metric_val。在这种情况下,如果您要执行嵌套条件运算符(我不会),则需要为其分配一些内容。这就是问题所在,您没有提供 "neither matches" 值。

据推测,您希望 "neither matches" 值为 metric_val,因此它的行为类似于您的 if/else if(本质上):

metric_val = x.includes(name) ? funcOne(a) : y.includes(name) ? funcTwo(a) : metric_val;
// -----------------------------------------------------------------------^^^^^^^^^^^^^

(您不需要在该表达式中使用括号,除非您希望它们用于强调。)

代码会抛出错误,因为如果值为 false,您需要在每个三元运算符中都有一个表达式。您可以为此使用 null

let metric_val = (x.includes(name)) ? funcOne(a) : (y.includes(name)) ? funcTwo(a) : null;

但这根本不是处理这个问题的好方法。如果您有 2 个值,那么 if-else 就可以了。否则创建一个数组对象,然后循环遍历它以分配正确的值。

const arr = [
    [x, funcOne],
    [y, funcTwo]
    ...
]
let found = arr.find(([arr]) => arr.includes(name))
if(found){
   metric_val = found[1](a)
}