Javascript 条件返回语句(if-else 语句的简写) [英] Javascript conditional return statement (Shorthand if-else statement)
问题描述
在 JavaScript 中编写速记 if-else 时,出现语法错误.这是我的代码:
While writing shorthand if-else in javascript,getting syntax error. Here is my code:
data && data.cod == '404' && return;
虽然当我使用正常的 if-else 时工作正常,如下所示:
Although works fine when I use normal if-else like below:
if(data && data.cod == '404') {return};
var temp = data && data.main && data.main.temp;
//Code here...
我知道,如果我使用像 return (data && data.cod == '404')?'true':'false';
这样的三元运算符,它工作正常,但我'我有条件地寻找回报",否则继续.
I know, it works fine if I use ternary operator like return (data && data.cod == '404')?'true':'false';
but I'm looking "return" on conditional basis otherwise continue further.
推荐答案
您试图做的是违反语法规则.
What you're trying to do is a violation of syntax rules.
return
关键字只能用在 返回声明
The return
keyword can only be used at the beginning of a return statement
在数据&&data.cod == '404' &&<something>
,您唯一可以放入 <something>
的是表达式,而不是语句.你不能把 return
放在那里.
In data && data.cod == '404' && <something>
, the only thing you can place in <something>
is an expression, not a statement. You can't put return
there.
要有条件地返回,请使用适当的 if
语句:
To return conditionally, use a proper if
statement:
if(data && data.cod == '404') {
return;
}
我建议不要像您尝试那样使用快捷方式作为执行具有副作用的代码的聪明"方式.条件运算符和布尔运算符的目的是产生一个值:
I would recommend against using shortcuts like you're trying to do as a "clever" way to execute code with side effects. The purpose of the conditional operator and boolean operators is to produce a value:
好:
var value = condition ? valueWhenTrue : valueWhenFalse;
差:
condition ? doSomething() : doSomethingElse();
您不应该这样做,即使语言允许您这样做.这不是条件运算符的用途,它会让试图理解您的代码的人感到困惑.
You shouldn't be doing this, even if the language allows you to do so. That's not what the conditional operator is intended for, and it's confusing for people trying to make sense of your code.
为此使用适当的 if
语句.这就是它的用途:
Use a proper if
statement for that. That's what it's for:
if (condition) {
doSomething();
} else {
doSomethingElse();
}
如果你真的想把它放在一行:
You can put it on one line if you really want to:
if (condition) { doSomething(); } else { doSomethingElse(); }
这篇关于Javascript 条件返回语句(if-else 语句的简写)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!