nodejs中的三元运算符

问题描述 投票:3回答:2

我试图在nodejs中使用三元运算符进行条件检查。

三元运算符在下面的场景中没有问题,工作正常。它在控制台中打印文本

{true ? (
  console.log("I am true")      
) : (
  console.log("I am not true")
)}

同样的情况不适用于以下情况,并且会引发跟随错误

让text =“我是真的”;

  ^^^^ 

SyntaxError:意外的标识符

{true ? (
  let text = "I am true";
  console.log(text);      
) : (
  console.log("I am not true")
)}

我无法理解为什么这种行为有所不同。

javascript node.js ternary-operator
2个回答
7
投票

在条件(三元)运算符中的?:之后的内容必须是表达式,而不是语句。表达式评估为一个值。变量赋值,如let text = "I am true";,是一个语句,而不是表达式 - 它做了某些事情(将“我对kazxswpoi变量赋予真实”)而不是评估某个值。

当这些括号需要计算为表达式时,您也不能在括号内使用分号。如果你真的想,你可以使用逗号运算符,虽然它有点令人困惑:

text

但是条件运算符仍然不适合这种情况 - 条件运算符求值为一个值(它本身就是一个表达式)。如果您不打算使用结果值,则应使用let text; (true ? ( text = "I am true", console.log(text) ) : ( console.log("I am not true") ))代替:

if/else

使用条件运算符的时间是您需要使用结果值时,例如:

let text;
if (true) {
  text = "I am true";
  console.log(text);
} else console.log("I am not true");

(请参阅此处如何使用条件运算的结果 - 它被分配给const condition = true; const text = condition ? 'I am true' : 'I am not true'; console.log(text);变量。)


1
投票

你不能在三元运算符中做那样的赋值。您需要执行以下操作:

text
© www.soinside.com 2019 - 2024. All rights reserved.