我正在尝试在 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 = "I am true";
,是一个语句,而不是一个表达式 - 它做某事(赋值“I对 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
变量。)
关于javascript - nodejs中的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176367/