我試圖寫一行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
?
我試圖寫一行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
?
你錯過了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);
好的dv。也許你會添加爲什麼。 –
這也是一個很好的方法+1 –
不是我倒票的人,但很可能是因爲它從來沒有回答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塊,因爲前兩個條件永遠不會滿足。
不要。不要。當您的代碼難以讀取和調試時,簡潔並不是一種美德。 – Quentin
雖然你可以嵌套三元條件爲什麼你要在地球上?閱讀/調試是非常糟糕的,你可能沒有得到如此多的性能提升。爲什麼不直接如果/其他塊? – IMTheNachoMan
@Quentin不是比'if else else else'更快嗎? – Eniss