5个小技巧让你写出更好的 JavaScript 条件语句

在使用 JavaScript 时,我们常常要写不少的条件语句。这里有五个小技巧,可以让你写出更干净、漂亮的条件语句。
1、使用 Array.includes 来处理多重条件
举个栗子 :
// 条件语句function test(fruit) {if (fruit == 'apple' || fruit == 'strawberry') {console.log('red');}}
function test(fruit) {// 把条件提取到数组中const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];if (redFruits.includes(fruit)) {console.log('red');}}
2、少写嵌套,尽早返回
如果没有提供水果,抛出错误。 如果该水果的数量大于 10,将其打印出来。 
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 {thrownewError('No fruit!');}}// 测试结果test(null); // 报错:No fruitstest('apple'); // 打印:redtest('apple', 20); // 打印:red,big quantity
1 个 if/else 语句来筛选无效的条件 3 层 if 语句嵌套(条件 1,2 & 3) 
/_ 当发现无效条件时尽早返回 _/function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];// 条件 1:尽早抛出错误if (!fruit) thrownewError('No fruit!');// 条件2:必须为红色if (redFruits.includes(fruit)) {console.log('red');// 条件 3:必须是大量存在if (quantity > 10) {console.log('big quantity');}}}
/_ 当发现无效条件时尽早返回 _/function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];if (!fruit) thrownewError('No fruit!'); // 条件 1:尽早抛出错误if (!redFruits.includes(fruit)) return; // 条件 2:当 fruit 不是红色的时候,直接返回console.log('red');// 条件 3:必须是大量存在if (quantity > 10) {console.log('big quantity');}}
这样的代码比较简短和直白,一个嵌套的 if 使得结构更加清晰。
条件反转会导致更多的思考过程(增加认知负担)。
Avoid Else, Return Early by Tim Oxley
StackOverflow discussion on if/else coding style
3、使用函数默认参数和解构
function test(fruit, quantity) {if (!fruit) return;const q = quantity || 1; // 如果没有提供 quantity,默认为 1console.log(`We have ${q}${fruit}!`);}//测试结果test('banana'); // We have 1 banana!test('apple', 2); // We have 2 apple!
function test(fruit, quantity = 1) { // 如果没有提供 quantity,默认为 1if (!fruit) return;console.log(`We have ${quantity}${fruit}!`);}//测试结果test('banana'); // We have 1 banana!test('apple', 2); // We have 2 apple!
function test(fruit) {// 如果有值,则打印出来if (fruit && fruit.name) {console.log (fruit.name);} else {console.log('unknown');}}//测试结果test(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple
观察上面的例子,当水果名称属性存在时,我们希望将其打印出来,否则打印『unknown』。
我们可以通过默认参数和解构赋值的方法来避免写出 fruit && fruit.name 这种条件。
// 解构 —— 只得到 name 属性// 默认参数为空对象 {}function test({name} = {}) {console.log (name || 'unknown');}//测试结果test(undefined); // unknowntest({ }); // unknowntest({ 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 get 函数
使用 Facebook 开源的 idx 库(需搭配 Babeljs)
这里有一个使用 Lodash 的例子:
// 使用 lodash 库提供的 _ 方法function test(fruit) {console.log(_.get(fruit, 'name', 'unknown'); // 获取属性 name 的值,如果没有,设为默认值 unknown}//测试结果test(undefined); // unknowntest({ }); // unknowntest({ name: 'apple', color: 'red' }); // apple
你可以在这里运行演示代码。另外,如果你偏爱函数式编程(FP),你可以选择使用 Lodash fp——函数式版本的 Lodash(方法名变为 get 或 getOr)。
4、相较于 switch,Map / Object 也许是更好的选择
让我们看下面的例子,我们想要根据颜色打印出各种水果:
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 = newMap().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);function test(color) {return fruitColor.get(color) || [];}
懒人版:重构语法
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!
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;// 条件:所有的水果都必须是红色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}
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!

