在用 JavaScript 工作時,我們經(jīng)常和條件語句打交道,這里有5條讓你寫出更好/干凈的條件語句的建議。
目錄:
1.多重判斷時使用 Array.includes
2.更少的嵌套,盡早 return
3.使用默認(rèn)參數(shù)和解構(gòu)
4.傾向于遍歷對象而不是 Switch 語句
5.對 所有/部分 判斷使用 Array.every & Array.some
6.總結(jié)
1.多重判斷時使用 Array.includes
讓我們看一下下面這個例子:
// conditionfunction test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); }}第一眼,上面這個例子看起來沒問題。如果我們有更多名字叫 cherry 和 cranberries 的紅色水果呢?我們準(zhǔn)備用更多的 || 來拓展條件語句嗎?
我們可以用 Array.includes (Array.includes)重寫條件語句。
function test(fruit) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); }}我們把紅色的水果(red fruits)這一判斷條件提取到一個數(shù)組。這樣一來,代碼看起來更整潔。
2.更少的嵌套,盡早 Return
讓我們拓展上一個例子讓它包含兩個條件。
如果沒有傳入?yún)?shù) fruit,拋出錯誤 接受 quantity 參數(shù),并且在 quantity 大于 10 時打印出來function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 條件 1: fruit 必須有值 if (fruit) { // 條件 2: 必須是red的 if (redFruits.includes(fruit)) { console.log('red'); // 條件 3: quantity大于10 if (quantity > 10) { console.log('big quantity'); } } } else { throw new Error('No fruit!'); }}// 測試結(jié)果test(null); // error: No fruitstest('apple'); // print: redtest('apple', 20); // print: red, big quantity在上面的代碼, 我們有:
1個 if/else 語句篩選出無效的語句 3層if嵌套語句 (條件 1, 2 & 3)我個人遵循的規(guī)則一般是在發(fā)現(xiàn)無效條件時,盡早Return。
/_ 當(dāng)發(fā)現(xiàn)無效語句時,盡早Return _/function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 條件 1: 盡早拋出錯誤 if (!fruit) throw new Error('No fruit!'); // 條件 2: 必須是紅色的 if (redFruits.includes(fruit)) { console.log('red'); // 條件 3: 必須是大質(zhì)量的 if (quantity > 10) { console.log('big quantity'); } }}這樣一來,我們少了一層嵌套語句。這種編碼風(fēng)格非常好,尤其是當(dāng)你有很長的if語句的時候(想象你需要滾動到最底層才知道還有else語句,這并不酷)
我們可以通過 倒置判斷條件 & 盡早return 進(jìn)一步減少if嵌套。看下面我們是怎么處理判斷 條件2 的:
/_ 當(dāng)發(fā)現(xiàn)無效語句時,盡早Return _/function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 條件 1: 盡早拋出錯誤 if (!fruit) throw new Error('No fruit!'); // 條件 2: 當(dāng)水果不是紅色時停止繼續(xù)執(zhí)行 if (!redFruits.includes(fruit)) return; console.log('red'); // 條件 3: 必須是大質(zhì)量的 if (quantity > 10) { console.log('big quantity'); }}
新聞熱點
疑難解答
圖片精選