简体   繁体   English

JavaScript三元运算符转换为完整的if / else语句问题

[英]JavaScript ternary operator into full if/else statement issue

I have following ternary statement: 我有以下三元声明:

$.history.init(function(url) {
        load(url == "" ? "#some-page" : url);
});

Which I have rewrote into: 我改写成了:

$.history.init(function(url) {
         load( 
               if( url == ""){ url = "#some-page"
               } else { url = url }
         );
 });

I now the is an error on line 3 if(url == "") , but I don't understand what error. 我现在是第3行的错误if(url == "") ,但我不明白什么错误。
Any suggestion much appreciated. 任何建议都非常感谢。

In JavaScript, an if is not an expression. 在JavaScript中, if 不是表达式。 It does not return a value and cannot be put inside a function call. 它不返回值,也不能放入函数调用中。 That is, this is not valid: 也就是说,这是无效的:

func(if (a) { ... } else { ... });

This is the main difference between if and ?: --the operator is an expression and returns a value; 这是if?:之间的主要区别?: - 运算符是一个表达式并返回一个值; if is a statement, does not return a value and cannot be used everywhere. if是一个语句, 返回值,并不能随处使用。

Your best bet if you have to avoid the ternary operator is to do something like: 如果你不得不避免使用三元运算符,最好的办法就是:

if (url == "") {
  url = "#some-page";
} 

load(url);

You can also achieve the same effect using || 您也可以使用||实现相同的效果 :

function (url) {
  load(url || "#some-page");
}

This is the shortest and most idiomatic way to write your code. 这是编写代码的最短且最惯用的方式。

if expressions dont return anything in JS. if表达式不返回JS中的任何内容。 So that basically does load(undefined) . 所以这基本上是load(undefined)

Try this instead: 试试这个:

if (url === '') {
  url = '#some-page';
}

load(url);

Note you don't need to else at all, because if the value is present you have nothing to change. 请注意,您根本不需要else ,因为如果值存在,则无需更改。

rewrite it as 将其重写为

$.history.init(function(url) {
        if( url == ""){ 
           url = "#some-page";
         }
         load( url );
 });

Your rewritten code is invalid. 您重写的代码无效。 Try this: 试试这个:

$.history.init(function(url) {
      if(url == "") {
         load("#some-page");
      } else {
         load(url);
      }
});

You need the if statement to be outside of the load function, ie 您需要if语句在load函数之外,即

$.history.init(function(url) {
    if (url === "") { 
        url = "#some-page";
    }
    load(url);
});

Note that you don't need the else clause as url = url is a redundant operation. 请注意,您不需要else子句,因为url = url是一个冗余操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM