一行if..else if .. else语句

问题描述:

我试图写一行if..elseif..else语句,但总是在else if一行if..else if .. else语句

var x = "192.168.1.1"; 
 
x = x == ("google.com") ? ("true google.com") : (("yahoo.com") ? ("true yahoo.com") : ("192.168.1.1")); 
 
console.log(x);

有什么我失踪?为什么它总是在else if

+3

不要。不要。当您的代码难以读取和调试时,简洁并不是一种美德。 – Quentin

+2

虽然你可以嵌套三元条件为什么你要在地球上?阅读/调试是非常糟糕的,你可能没有得到如此多的性能提升。为什么不直接如果/其他块? – IMTheNachoMan

+0

@Quentin不是比'if else else else'更快吗? – Eniss

你错过了x == (""yahoo.com"")声明

var x = "192.168.1.1"; 
 
x = (x == "google.com") ? 
 
     "true google.com" : 
 
     (x == "yahoo.com") ? 
 
      "true yahoo.com" : 
 
     "192.168.1.1"; 
 
// --------------------------------------------^^^^^^^^^^^^^^^^------------------------------------ 
 
console.log(x);

但它会随着if - else if - else报表更具可读性。如果它会降低可读性,请不要使代码简洁。

这不回答这个问题

为什么总是去else if

,但它可能与

帮有什么我失踪?

是的,你错了一些清晰的进一步使用和清晰的模式,如何得到给定的字符串另一个字符串。

您可以使用一个易于维护键值的对象。

values = { 
    "google.com": "true google.com", 
    "yahoo.com": "true yahoo.com", 
    default : "192.168.1.1" 
}; 

呼叫工作具有默认操作||(逻辑OR):

x = values[x] || values.default; 

var x = "192.168.1.1", 
 
    values = { 
 
     "google.com": "true google.com", 
 
     "yahoo.com": "true yahoo.com", 
 
     default : "192.168.1.1" 
 
    }; 
 

 
x = values[x] || values.default; 
 
console.log(x);

+0

好的dv。也许你会添加为什么。 –

+0

这也是一个很好的方法+1 –

+0

不是我倒票的人,但很可能是因为它从来没有回答OP的问题,但给出了另一种方法。我个人并不反对,但我确实知道一些关于这些的东西可以得到一些分析。 – Keith

你的三元操作

x = x == ("google.com") ? ("true google.com") : (("yahoo.com") ? ("true yahoo.com") : ("192.168.1.1")); 

可以被认为是if-else if-else块如下:

if(x == ("google.com")) { 
    x = "true google.com"; 
} 
else { 
    if("yahoo.com") { 
     x = "true yahoo.com"; //Always true since it is a non-empty string 
    } 
    else { 
     x = "192.168.1.1" 
    } 
} 

那么既然要初始化X设置为“192.168.1.1”,这显然是不等于指定的字符串(“google.com “)在第一个条件(if块)。所以它移动到else块并评估else块内的if条件。该if块反过来只检查字符串文字“yahoo.com”是否为空。由于它不是空的,条件得到满足。

为了您的目的,您需要将其从if("yahoo.com")更改为x == if("yahoo.com")。但是,一旦你做了这个改变,它总是会去else块,因为前两个条件永远不会满足。