【譯】javascript中寫好條件語句的五個技巧

當用JavaScript來工作的時候,我們需要處理很多的條件判斷,這裡有五個小技巧能幫助你寫出更好/更清晰的條件語句。
1. 多重判斷中使用Array.includes
我們看下下面這個例子:
// condition function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } } 複製程式碼
乍一看,上面的例子看起來還可以哦。但是,如果新增更多的紅色的水果,比如 cherry
和 cranberries
,那會怎樣呢?你會使用更多的 ||
來擴充套件條件語句嗎?
我們可以通過 Array.includes
(Array.includes)來重寫上面的條件語句。如下:
function test(fruit) { // extract conditions to array const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } } 複製程式碼
我們提取 red fruits
(條件判斷)到一個數組中。通過這樣做,程式碼看起來更加整潔了。
2. 少巢狀,早返回
我們擴充套件上面的例子,讓它包含多兩個條件:
- 如果沒有傳入fruit引數,丟擲錯誤
- 接受quantity引數並在其超出10打印出來
function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // condition 1: fruit must has value if (fruit) { // condition 2: must be red if (redFruits.includes(fruit)) { console.log('red'); // condition 3: must be big quantity if (quantity > 10) { console.log('big quantity'); } } } else { throw new Error('No fruit!'); } } // test results test(null); // error: No fruits test('apple'); // print: red test('apple', 20); // print: red, big quantity 複製程式碼
看下上面的程式碼,我們捋下:
- 1個if/else語句篩出無效的條件語句
- 3層巢狀的語句(條件1,2和3)
我個人遵守的準則是 發現無效的條件時,及早return 。
/_ return early when invalid conditions found _/ function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // condition 1: throw error early if (!fruit) throw new Error('No fruit!'); // condition 2: must be red if (redFruits.includes(fruit)) { console.log('red'); // condition 3: must be big quantity if (quantity > 10) { console.log('big quantity'); } } } 複製程式碼
通過及早return,我們減少了一層巢狀語句。這種編碼風格很贊,尤其是當你有很長的if語句(可以想象下你需要滾動很長才知道有else語句,一點都不酷)。
(針對上面例子)我們可以通過倒置判斷條件和及早return來進一步減少if巢狀。看下面我們是怎麼處理條件2的:
/_ return early when invalid conditions found _/ function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red console.log('red'); // condition 3: must be big quantity if (quantity > 10) { console.log('big quantity'); } } 複製程式碼
通過倒置條件2,我們避免了巢狀語句。這個技巧很有用:當我們處理很長的邏輯,並且希望能夠在條件不滿足時能夠停下來進行處理。
而且,這樣做並不難。問下自己,這個版本(沒有條件巢狀)是不是比之前版本(兩層巢狀)更好/可讀性更高呢?
但是,對於我來說,我會保留先前的版本(包含兩層巢狀)。因為:
- 程式碼較短且直接,巢狀if更加清晰
- 倒置判斷條件可能增加思考負擔(增加認知負荷)
因此,應當 儘量減少巢狀和及早return,但是不要過度 。如果你感興趣,你可以看下面的一篇文章和StackOverflow上的討論,進一步瞭解:
- Avoid Else, Return Early by Tim Oxley
- StackOverflow discussion on if/else coding style
3. 使用預設引數和解構
我猜你對下面的程式碼有些熟悉,在JavaScript中我們總需要檢查 null/undefined
值和指定預設值。
function test(fruit, quantity) { if (!fruit) return; const q = quantity || 1; // if quantity not provided, default to one console.log(`We have ${q} ${fruit}!`); } //test results test('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple! 複製程式碼
事實上,我們可以通過宣告預設的函式引數來消除變數 q
。
function test(fruit, quantity = 1) { // if quantity not provided, default to one if (!fruit) return; console.log(`We have ${quantity} ${fruit}!`); } //test results test('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple! 複製程式碼
很容易且很直觀!注意,每個宣告都有自己預設引數。舉個例子,我們也可以給 fruit
設定一個預設值: function test(fruit = 'unknown', quantity = 1)
。
如果我們的 fruit
是一個物件會怎樣呢?我們能分配一個預設引數嗎?
function test(fruit) { // printing fruit name if value provided if (fruit && fruit.name){ console.log (fruit.name); } else { console.log('unknown'); } } //test results test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple 複製程式碼
上面的例子中,當存在fruit name的時候我們打印出水果名,否則打印出unknown。我們可以通過設定預設引數和解構來避免判斷條件 fruit && fruit.name
。
// destructing - get name property only // assign default empty object {} function test({name} = {}) { console.log (name || 'unknown'); } //test results test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple 複製程式碼
由於我們只需要 name
屬性,我們可以使用 {name}
來解構引數,然後我們就可以使用 name
代替 fruit.name
了。
我們也聲明瞭一個空物件 {}
作為預設值。如果我們沒有這麼做,你會得到一個無法對undefined或null解構的錯誤。因為在undefined中沒有 name
屬性。
如果你不介意使用第三方庫,有一些方式能減少null的檢查:
- 使用Lodash get 函式
- 臉書的開源庫 idx (配合babeljs使用)
這有一個使用Lodash的例子:
// Include lodash library, you will get _ function test(fruit) { console.log(__.get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown' } //test results test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple 複製程式碼
你可以在JSBIN這裡執行demo程式碼,如果你是函數語言程式設計的粉絲,你可以選擇 Lodash fp ,Lodash的函式式版本(方法變更為 get
或者 getOr
)。
4. 傾向物件遍歷而不是switch語句
看下下面的程式碼,我們想基於color來列印水果。
function test(color) { // use switch case to find fruits in color switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } } //test results test(null); // [] test('yellow'); // ['banana', 'pineapple'] 複製程式碼
上面的程式碼看似沒問題,但是多少有些冗餘。用遍歷物件(object literal)來實現相同的結果,語法看起來更加簡潔:
// use object literal to find fruits in color const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; } 複製程式碼
或者,你可以使用Map來實現相同的結果:
// use Map to find fruits in color 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語句嗎?不要限制自己做這個。個人來說,我會盡可能使用物件遍歷,但是不會嚴格遵守它,而是使用對當前場景更有意義的方式。
Todd Motto 有篇對switch語句和遍歷物件深層次對比的文章,你可以戳這裡來檢視。
TL;DL;重構語法
針對上面的例子,我們可以通過 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) { // use Array filter to find fruits in color return fruits.filter(f => f.color == color); } 複製程式碼
有著不止一種方法能夠實現相同的結果,我們以上展示了4種。編碼是快樂的!
5. 對 全部/部分判斷 使用Array.every/Array.some
最後一個技巧是使用Javascript的內建陣列函式來減少程式碼的行數。看下下面的程式碼,我們想檢視所有的水果是否是紅色:
const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; function test() { let isAllRed = true; // condition: all fruits must be red 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() { // condition: short way, all fruits must be red 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() { // condition: if any fruit is red const isAnyRed = fruits.some(f => f.color == 'red'); console.log(isAnyRed); // true } 複製程式碼
總結
讓我們一起寫出可讀性更高的程式碼。我希望你能從這篇文章學到些新東西。
這是全部內容。祝你編碼愉快!
文章首發: github.com/reng99/blog…
更多內容: github.com/reng99/blog…