Javascript 条件返回语句(if-else 语句的简写)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28104765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:25:26  来源:igfitidea点击:

Javascript conditional return statement (Shorthand if-else statement)

javascriptjqueryternary-operator

提问by Vivek Pratap Singh

While writing shorthand if-else in javascript,getting syntax error. Here is my code:

在 javascript 中编写速记 if-else 时,出现语法错误。这是我的代码:

data && data.cod   ==  '404' && return;

Although works fine when I use normal if-else like below:

虽然当我使用正常的 if-else 时工作正常,如下所示:

        if(data && data.cod   ==  '404') {return};
        var temp        =   data && data.main && data.main.temp;
       //Code here...

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.

我知道,如果我像这样使用三元运算符,它会工作得很好,return (data && data.cod == '404')?'true':'false';但我正在寻找有条件的“返回”,否则会进一步继续。

回答by JLRishe

What you're trying to do is a violation of syntax rules.

你试图做的是违反语法规则。

The returnkeyword can only be used at the beginning of a return statement

return关键字只能在开始时使用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 returnthere.

在 中data && data.cod == '404' && <something>,您唯一可以放入的<something>是表达式,而不是语句。你不能放在return那里。

To return conditionally, use a proper ifstatement:

要有条件地返回,请使用正确的if语句:

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:

我建议不要使用像您尝试使用的快捷方式那样作为执行带有副作用的代码的“聪明”方式。条件运算符和布尔运算符的目的是产生一个值

Good:

好的:

var value = condition ? valueWhenTrue : valueWhenFalse;

Bad:

坏的:

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.

你不应该这样做,即使语言允许你这样做。这不是条件运算符的用途,它让试图理解您的代码的人感到困惑。

Use a proper ifstatement for that. That's what it's for:

if为此使用适当的语句。这就是它的用途:

if (condition) {
    doSomething();
} else {
    doSomethingElse();
}

You can put it on one line if you really want to:

如果你真的想要,你可以把它放在一行上:

if (condition) { doSomething(); } else { doSomethingElse(); }

回答by Ba5t14n

Well then just write the return in the if

那么只需在 if 中写入返回值

var result = (data && data.cod   ==  '404') 
if (result) {
  return result;
} else {
    //otherwise
}