- 原文地址:5 Tips to Write Better Conditionals in JavaScript
- 原文做者:Jecelyn Yeen
- 譯文出自:掘金翻譯計劃
- 本文永久連接:github.com/xitu/gold-m…
- 譯者:Hopsken
- 校對者:ThomasWhyne Park-ma
在使用 JavaScript 時,咱們經常要寫很多的條件語句。這裏有五個小技巧,可讓你寫出更乾淨、漂亮的條件語句。javascript
舉個栗子 🌰:前端
// 條件語句
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
複製代碼
乍一看,這麼寫彷佛沒什麼大問題。然而,若是咱們想要匹配更多的紅色水果呢,比方說『櫻桃』和『蔓越莓』?咱們是否是得用更多的 ||
來擴展這條語句?java
咱們可使用 Array.includes
(Array.includes) 重寫以上條件句。android
function test(fruit) {
// 把條件提取到數組中
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}
複製代碼
咱們把紅色的水果
(條件)都提取到一個數組中,這使得咱們的代碼看起來更加整潔。ios
讓咱們爲以前的例子添加兩個條件:git
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 條件 1:fruit 必須有值
if (fruit) {
// 條件 2:必須爲紅色
if (redFruits.includes(fruit)) {
console.log('red');
// 條件 3:必須是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
} else {
throw new Error('No fruit!');
}
}
// 測試結果
test(null); // 報錯:No fruits
test('apple'); // 打印:red
test('apple', 20); // 打印:red,big quantity
複製代碼
讓咱們來仔細看看上面的代碼,咱們有:github
就我我的而言,我遵循的一個總的規則是當發現無效條件時儘早返回。編程
/_ 當發現無效條件時儘早返回 _/
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:必須是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
}
複製代碼
如此一來,咱們就少寫了一層嵌套。這是種很好的代碼風格,尤爲是在 if 語句很長的時候(試想一下,你得滾動到底部才能知道那兒還有個 else 語句,是否是有點不爽)。後端
若是反轉一下條件,咱們還能夠進一步地減小嵌套層級。注意觀察下面的條件 2 語句,看看是如何作到這點的:數組
/_ 當發現無效條件時儘早返回 _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!'); // 條件 1:儘早拋出錯誤
if (!redFruits.includes(fruit)) return; // 條件 2:當 fruit 不是紅色的時候,直接返回
console.log('red');
// 條件 3:必須是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
複製代碼
經過反轉條件 2 的條件,如今咱們的代碼已經沒有嵌套了。當咱們代碼的邏輯鏈很長,而且但願當某個條件不知足時再也不執行以後流程時,這個技巧會很好用。
然而,並無任何硬性規則要求你這麼作。這取決於你本身,對你而言,這個版本的代碼(沒有嵌套)是否要比以前那個版本(條件 2 有嵌套)的更好、可讀性更強?
是個人話,我會選擇前一個版本(條件 2 有嵌套)。緣由在於:
所以,始終追求更少的嵌套,更早地返回,可是不要過分。感興趣的話,這裏有篇關於這個問題的文章以及 StackOverflow 上的討論:
我猜你也許很熟悉如下的代碼,在 JavaScript 中咱們常常須要檢查 null
/ undefined
並賦予默認值:
function test(fruit, quantity) {
if (!fruit) return;
const q = quantity || 1; // 若是沒有提供 quantity,默認爲 1
console.log(`We have ${q} ${fruit}!`);
}
//測試結果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
複製代碼
事實上,咱們能夠經過函數的默認參數來去掉變量 q
。
function test(fruit, quantity = 1) { // 若是沒有提供 quantity,默認爲 1
if (!fruit) return;
console.log(`We have ${quantity} ${fruit}!`);
}
//測試結果
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!
複製代碼
是否是更加簡單、直白了?請注意,全部的函數參數均可以有其默認值。舉例來講,咱們一樣能夠爲 fruit
賦予一個默認值:function test(fruit = 'unknown', quantity = 1)
。
那麼若是 fruit
是一個對象(Object)呢?咱們還可使用默認參數嗎?
function test(fruit) {
// 若是有值,則打印出來
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
//測試結果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
複製代碼
觀察上面的例子,當水果名稱屬性存在時,咱們但願將其打印出來,不然打印『unknown』。咱們能夠經過默認參數和解構賦值的方法來避免寫出 fruit && fruit.name
這種條件。
// 解構 —— 只獲得 name 屬性
// 默認參數爲空對象 {}
function test({name} = {}) {
console.log (name || 'unknown');
}
//測試結果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
複製代碼
既然咱們只須要 fruit 的 name
屬性,咱們可使用 {name}
來將其解構出來,以後咱們就能夠在代碼中使用 name
變量來取代 fruit.name
。
咱們還使用 {}
做爲其默認值。若是咱們不這麼作的話,在執行 test(undefined)
時,你會獲得一個錯誤 Cannot destructure property name of 'undefined' or 'null'.
,由於 undefined
上並無 name
屬性。(譯者注:這裏不太準確,其實由於解構只適用於對象(Object),而不是由於undefined
上並無 name
屬性(空對象上也沒有)。參考解構賦值 - MDN)
若是你不介意使用第三方庫的話,有一些方法能夠幫助減小空值(null)檢查:
這裏有一個使用 Lodash 的例子:
// 使用 lodash 庫提供的 _ 方法
function test(fruit) {
console.log(_.get(fruit, 'name', 'unknown'); // 獲取屬性 name 的值,若是沒有,設爲默認值 unknown
}
//測試結果
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
複製代碼
你能夠在這裏運行演示代碼。另外,若是你偏心函數式編程(FP),你能夠選擇使用 Lodash fp——函數式版本的 Lodash(方法名變爲 get
或 getOr
)。
讓咱們看下面的例子,咱們想要根據顏色打印出各類水果:
function test(color) {
// 使用 switch case 來找到對應顏色的水果
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
//測試結果
test(null); // []
test('yellow'); // ['banana', 'pineapple']
複製代碼
上面的代碼看上去並無錯,可是就我我的而言,它看上去很冗長。一樣的結果能夠經過對象字面量來實現,語法也更加簡潔:
// 使用對象字面量來找到對應顏色的水果
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
複製代碼
或者,你也可使用 Map 來實現一樣的效果:
// 使用 Map 來找到對應顏色的水果
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
複製代碼
Map 是 ES2015 引入的新的對象類型,容許你存放鍵值對。
那是否是說咱們應該禁止使用 switch 語句? 別把本身限制住。我本身會在任何可能的時候使用對象字面量,可是這並非說我就不用 switch,這得視場景而定。
Todd Motto 有一篇文章深刻討論了 switch 語句和對象字面量,你也許會想看看。
就以上的例子,事實上咱們能夠經過重構咱們的代碼,使用 Array.filter
實現一樣的效果。
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'strawberry', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'pineapple', color: 'yellow' },
{ name: 'grape', color: 'purple' },
{ name: 'plum', color: 'purple' }
];
function test(color) {
// 使用 Array filter 來找到對應顏色的水果
return fruits.filter(f => f.color == color);
}
複製代碼
解決問題的方法永遠不僅一種。對於這個例子咱們展現了四種實現方法。Coding is fun!
最後一個小技巧更多地是關於使用新的(也不是很新了)JavaScript 數組函數來減小代碼行數。觀察如下的代碼,咱們想要檢查是否全部的水果都是紅色的:
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
let isAllRed = true;
// 條件:全部的水果都必須是紅色
for (let f of fruits) {
if (!isAllRed) break;
isAllRed = (f.color == 'red');
}
console.log(isAllRed); // false
}
複製代碼
這段代碼也太長了!咱們能夠經過 Array.every
來縮減代碼:
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
// 條件:(簡短形式)全部的水果都必須是紅色
const isAllRed = fruits.every(f => f.color == 'red');
console.log(isAllRed); // false
}
複製代碼
清晰多了對吧?相似的,若是咱們想要檢查是否有至少一個水果是紅色的,咱們可使用 Array.some
僅用一行代碼就實現出來。
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
function test() {
// 條件:至少一個水果是紅色的
const isAnyRed = fruits.some(f => f.color == 'red');
console.log(isAnyRed); // true
}
複製代碼
讓咱們一塊兒寫出可讀性更高的代碼吧。但願這篇文章能給大家帶來一些幫助。
就是這樣啦。Happy coding!
若是發現譯文存在錯誤或其餘須要改進的地方,歡迎到 掘金翻譯計劃 對譯文進行修改並 PR,也可得到相應獎勵積分。文章開頭的 本文永久連接 即爲本文在 GitHub 上的 MarkDown 連接。
掘金翻譯計劃 是一個翻譯優質互聯網技術文章的社區,文章來源爲 掘金 上的英文分享文章。內容覆蓋 Android、iOS、前端、後端、區塊鏈、產品、設計、人工智能等領域,想要查看更多優質譯文請持續關注 掘金翻譯計劃、官方微博、知乎專欄。