nodejs中的三元运算符

ternary operator in nodejs

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

三元运算符在以下情况下工作正常,没有问题。它在控制台中打印文本

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

在下面的情况下同样不起作用,它会抛出以下错误

let text = "I am true";

  ^^^^ 

SyntaxError: Unexpected identifier

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

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

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

let text = myCondition
              ? "I am true"
              : "I am not true"

条件(三元)运算符中 ?: 后面的内容必须是 表达式 ,而不是语句。表达式求值。变量赋值,如 let text = "I am true";,是一个 语句 ,而不是一个表达式 - 它 某事(将 "I am true" 赋值给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);

(在此处查看条件运算的结果如何被 使用 - 它被分配给 text 变量。)

let text;

true ? (text = "I am true") : (text = "I am not true");

console.log(text);