Hem*_*ari 3 javascript ternary-operator node.js
我试图在nodejs中使用三元运算符进行条件检查.
三元运算符在下面的场景中没有问题,工作正常.它在控制台中打印文本
{true ? (
console.log("I am true")
) : (
console.log("I am not true")
)}
Run Code Online (Sandbox Code Playgroud)
同样的情况不适用于以下情况,并且会引发跟随错误
让text ="我是真的";
Run Code Online (Sandbox Code Playgroud)^^^^SyntaxError:意外的标识符
{true ? (
let text = "I am true";
console.log(text);
) : (
console.log("I am not true")
)}Run Code Online (Sandbox Code Playgroud)
我无法理解为什么这种行为有所不同.
接下来的?或:在条件(三元)操作者必须一个表达式,而不是语句.表达式评估为一个值.变量赋值就像let text = "I am true";是一个语句,而不是表达式 - 它做了某些事情(为text变量赋予"我是真的" )而不是评估某个值.
当这些括号需要计算为表达式时,您也不能在括号内使用分号.如果你真的想,你可以使用逗号运算符,虽然它有点令人困惑:
let text;
(true ? (
text = "I am true",
console.log(text)
) : (
console.log("I am not true")
))Run Code Online (Sandbox Code Playgroud)
但是条件运算符仍然不适合这种情况 - 条件运算符求值为一个值(它本身就是一个表达式).如果您不打算使用结果值,则应使用if/else:
let text;
if (true) {
text = "I am true";
console.log(text);
} else console.log("I am not true");Run Code Online (Sandbox Code Playgroud)
使用条件运算符的时间是您需要使用结果值时,例如:
const condition = true;
const text = condition ? 'I am true' : 'I am not true';
console.log(text);Run Code Online (Sandbox Code Playgroud)
(请参阅如何有条件操作的结果被用在这里-它被分配给text变量.)
| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |