在javascript流程控制中并沒有像java中有g(shù)oto跳轉(zhuǎn),所以基本上都是用if...if 或者if...else if來控制。但是,如果流程有比較多的分支時(shí),代碼會(huì)顯得特別的腫。本文介紹了一種簡單的消腫方法,請(qǐng)參考。
1.明白if...if 和if...else if的區(qū)別
if (條件1)
{
//語句1
}
if (條件2)
{
//語句2
}
這種格式中,程序會(huì)依次判斷條件1和條件2是否成立并根據(jù)結(jié)果決定是否執(zhí)行語句1和語句2,也就是說,第一個(gè) if 塊和第二個(gè) if 塊沒有影響(除非在執(zhí)行第一個(gè) if 塊的時(shí)候就兇殘地 return 了)
而下面這種格式,
if (條件1)
{
//語句1
}
else if (條件2)
{
//語句2
}
if 塊和 else if 塊本質(zhì)上是互斥的!也就是說,一旦語句1得到了執(zhí)行,程序會(huì)跳過 else if 塊,else if 塊中的判斷語句以及語句2一定會(huì)被跳過;同時(shí)語句2的執(zhí)行也暗含了條件1判斷失敗和語句1沒有執(zhí)行;當(dāng)然還有第3個(gè)情況,就是條件1和條件2都判斷失敗,語句1和語句2都沒有得到執(zhí)行。
2.未優(yōu)化的代碼
function program(a) {
if (a === 'java') {
console.log('the language is: ' + a);
} else if (a === 'object c') {
console.log('the language is: ' + a);
} else if (a === 'js') {
console.log('the language is: ' + a);
}
// 中間還有若干個(gè) else if ...
else {
console.log('the language is: php');
}
}
program('java'); // the language is: java
一個(gè)詞來形容:惡心
3.嘗試優(yōu)化
原理:映射對(duì)應(yīng)
const programs = {
java: function (a) {
console.log('the language is: ' + a);
},
object: function (a) {
console.log('the language is: ' + a);
},
js: function (a) {
console.log('the language is: ' + a);
}
};
(function sayPrograms(){
return programs['java']('javaaaaaaaa'); // the language is: javaaaaaaaa
})();
對(duì)于if - else-if - else 類型的處理:使用try-catch。
const programs = {
java: function (a) {
console.log('the language is: ' + a);
},
object: function (a) {
console.log('the language is: ' + a);
},
js: function (a) {
console.log('the language is: ' + a);
}
};
try {
(function sayPrograms() {
return programs['java']('javaaaaaaaa');
})();
} catch (err) {
console.log('the language is: php');
}