譯者按: 試着不用if擼代碼,是件很有趣的事,而且,萬一你領會了什么是“數據即代碼,代碼即數據”呢?
為了保證可讀性,本文采用意譯而非直譯。另外,本文版權歸原作者所有,翻譯僅用於學習。
我在教新手編程時,喜歡給他們一些小小的挑戰,比如:不使用if語句(或者三元運算符、switch語句等)解決一些編程問題。
這樣做有什么意義嗎?
事實上,它可以迫使你從不同的角度尋找解決方法,也許可以找到更好的方法。
當然,使用if語句沒有任何不對的地方。但是,不使用if的話,有時候可以增加代碼的可讀性。這一點並不是絕對的,如果完全不使用if語句的話,代碼可讀性也許會更差。這需要你根據不同情況去判斷。
而且,不用if的話不只是影響可讀性。在這背后隱含着更加深刻的道理。通過了解本文的代碼示例,你可以發現,如果不使用if語句的話,你的代碼會更加接近代碼即數據的概念。
另外,當你嘗試不使用if語句去編程時,也是一件非常有意思的事情。
示例1: 統計數組中的奇數
假設我們有一個整數數組arrayOfIntegers,現在需要統計其中奇數的個數:
const arrayOfIntegers = [1, 4, 5, 9, 0, -1, 5];
使用if
let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); if (remainder === 1) { counter++; } }); console.log(counter);
不用if
let counter = 0; arrayOfIntegers.forEach((integer) => { const remainder = Math.abs(integer % 2); counter += remainder; }); console.log(counter);
示例2: 判斷工作日和周末不用if時,我們巧妙地利用了奇數與偶數的特性,它們除以2的余數分別是0和1。
給定一個日期(比如new Date()),判斷它是工作日還是周末,分別返回”weekend”和”weekday”。
使用if
const weekendOrWeekday = (inputDate) => { const day = inputDate.getDay(); if (day === 0 || day === 6) { return 'weekend'; } return 'weekday'; // Or, for ternary fans: // return (day === 0 || day === 6) ? 'weekend' : 'weekday'; }; console.log(weekendOrWeekday(new Date()));
不用if
const weekendOrWeekday = (inputDate) => { const day = inputDate.getDay(); return weekendOrWeekday.labels[day] || weekendOrWeekday.labels['default']; }; weekendOrWeekday.labels = { 0: 'weekend', 6: 'weekend', default: 'weekday' }; console.log(weekendOrWeekday(new Date()));
你是否發現if語句中其實隱含着一些信息呢?它告訴我們哪一天是周末,哪一天是工作日。因此,要去掉if語句的話,我們只需要把這些信息寫入weekendOrWeekday.labels對象,然后直接使用它就好了。
廣告: 如果你需要監控線上JavaScript代碼的錯誤的話,歡迎免費使用Fundebug!
示例3: doubler函數
寫一個doubler函數,它會根據參數的類型,進行不同的操作:
- 如果參數是數字,則乘以2(i.e.
5 => 10
,-10 => -20
); - 如果參數是字符串,則每個字符重復2次 (i.e.
'hello' => 'hheelloo'
); - 如果參數是函數,則調用2次;
- 如果參數是數組,則將每一個元素作為參數,調用doubler函數
- 如果參數是對象,則將每個屬性值作為參數,調用doubler函數
使用switch
const doubler = (input) => { switch (typeof input) { case 'number': return input + input; case 'string': return input .split('') .map((letter) => letter + letter) .join(''); case 'object': Object.keys(input) .map((key) => (input[key] = doubler(input[key]))); return input; case 'function': input(); input(); } }; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }), );
不用switch
可知,我將每一種參數類型對應的操作綁定到了doubler.operationsByType,這樣不需要switch語句,就可以實現doubler函數了。
const doubler = (input) => { return doubler.operationsByType[typeof input](input); }; doubler.operationsByType = { number: (input) => input + input, string: (input) => input .split('') .map((letter) => letter + letter) .join(''), function: (input) => { input(); input(); }, object: (input) => { Object.keys(input) .map((key) => (input[key] = doubler(input[key]))); return input; }, }; console.log(doubler(-10)); console.log(doubler('hey')); console.log(doubler([5, 'hello'])); console.log(doubler({ a: 5, b: 'hello' })); console.log( doubler(function() { console.log('call-me'); }), );
關於Fundebug
Fundebug專注於JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了6億+錯誤事件,得到了Google、360、金山軟件等眾多知名用戶的認可。歡迎免費試用!
版權聲明:
轉載時請注明作者Fundebug以及本文地址:
https://blog.fundebug.com/2017/11/06/write-javascript-without-if/