有什么不同?为什么它在函数 a() 中得到错误?
function a(){
1 == 1 ? return true: ""; // Uncaught SyntaxError: Unexpected token return
}
function b(){
1 == 1 ? console.log(true):""; // correct
}
function c(){
if (1==1) return true; // correct
}
Run Code Online (Sandbox Code Playgroud)
return是一个语句:它只能独立存在,就像一个if语句,不能被解析为一个值。条件运算符仅需要值(表达式)。它的语法是:
cond ? expr1 : expr2
Run Code Online (Sandbox Code Playgroud)
其中cond、expr1、 和expr2都是表达式。整个条件运算符将评估为expr1是否cond为真,expr2否则为真。
同样,这是无效的:
1 === 1
? if (foo) {
// do something
}
: ''
Run Code Online (Sandbox Code Playgroud)
您在条件运算符的?和之后放置的内容必须始终计算为一个值- 也就是说,它只能是一个表达式。,只是一个语句,不能计算为一个值(就像一个语句不能计算为一个值)。:returnif
console.log另一方面,是一个表达式,其计算结果为undefined。
如果您只想在true满足条件时返回a,那么您将不得不使用成熟的if:
function a() {
if (1 == 1) {
return true;
}
// other statements here
}
Run Code Online (Sandbox Code Playgroud)
如果您想在true满足条件时返回,否则返回空字符串,那么您可以将return放在左侧并使用条件运算符:
function a() {
return 1 == 1
? true
: '';
}
Run Code Online (Sandbox Code Playgroud)
当您需要有条件地创建表达式时,请使用条件运算符。如果您需要执行除创建条件表达式以外的任何操作(例如,如果您想要在return满足条件时获得特定值,否则继续执行函数的其余部分),您应该if改用。
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |