如何优雅的编写JavaScript(ES6)中的条件语句
我们使用 JavaScript 做前端开发在时,经常需要处理很多条件语句,这里分享一些 coding 小技巧,可以让你编写更好,更清晰的条件语句。
多个条件如何处理
我们来看看下面的例子:
function test(animal) { if (animal == 'cat' || animal == 'dog'||animal == 'cattle') { console.log('yes'); } }
test
函数中的条件语句看起来是没什么问题,但是如果再加几种呢?比如说sheep、pig、chicken
,这时候在看我们的条件语句,就已经十分臃肿了。
function test(animal) { if (animal == 'cat' || animal == 'dog'||animal == 'cattle'||animal == 'sheep'||animal == 'pig'||animal == 'chicken') { console.log('yes'); } }
这段代码看起来可读性以及可维护性已经很差了,如果再加上一些条件,感觉你看见了也会很烦躁。逻辑或||
显然已经不太适合这种场景了,我们可以使用 Array.includes()
重写上面的条件语句。
function test(animal) { // 条件提取到数组中 const yesArr = ['cat', 'dog', 'cherry', 'cattle','sheep','pig','chicken']; if (yesArr.includes(animal)) { console.log('yes'); } }
这样写一下是不是就很清晰,代码看起来也更整洁了。
恰到好处的 return 语句
让我们扩展前面的示例,再包含另外两个条件:
- 如果没有提供某种动物/非动物,抛出错误
- 接受动物数量
number
(数量)参数,如果超过 20,则并打印相关信息。
function test(animal, number) { const yesArr = ['cat', 'dog', 'cherry', 'cattle','sheep','pig','chicken']; // 条件 1:animal 必须有值 if (animal) { // 条件 2:必须为 yesArr 中的动物 if (redFruits.includes(animal)) { console.log('yes'); // 条件 3:数量必须大于 10 if (number > 20) { console.log('quite a lot'); } } } else { throw new Error('No animal!'); } } // 测试结果 test(null); // 抛出错误:No animal! test('cat'); // 打印:yes test('cat', 20); // 打印:yes,quite a lot
这是我们平时随手就来的代码,看起来是没毛病,但是呢是否有可优化的空间和余地呢? 看看上面的代码,我们有:
- 1 个 if …else 语句过滤掉无效条件
- 3 层 if 语句嵌套(分别是条件 1,2 和 3)
在发现无效条件时提前throw new Error
。试试看
function test(animal, number) { const yesArr = ['cat', 'dog', 'cherry', 'cattle','sheep','pig','chicken']; // 条件 1:animal 必须有值,否则提前抛出错误 if (!animal) throw new Error('No animal!'); // 条件 2:必须为 yesArr 中的动物 if (redFruits.includes(animal)) { console.log('yes'); // 条件 3:数量必须大于 10 if (number > 20) { console.log('quite a lot'); } } } // 测试结果 test(null); // 抛出错误:No animal! test('cat'); // 打印:yes test('cat', 20); // 打印:yes,quite a lot
可以看到,减少一层嵌套,看起来已经舒服了不少。我们在看公司老项目时,长篇大论的if(){}else if(){}
是否让你痛哭流涕,一边哭泣一 边 mmp 还不忘慢慢寻找问题到底出在哪?
回归正题,如果通过反转条件并提前 return ,我们可以进一步减少嵌套。 请查看下面的条件 2 ,看看我们是如何做到的:
function test(animal, number) { const yesArr = ['cat', 'dog', 'cherry', 'cattle','sheep','pig','chicken']; // 条件 1:animal 必须有值,否则提前抛出错误 if (!animal) throw new Error('No animal!'); // 条件 2:必须为 yesArr 中的动物 if (!redFruits.includes(animal)) return // 条件 3:数量必须大于 10 if (number > 20) { console.log('quite a lot'); } } // 测试结果 test(null); // 抛出错误:No animal! test('cat'); // 打印:yes test('cat', 20); // 打印:yes,quite a lot
可以看到,减少一个条件语句的使用,不但可以节约性能,更能够极大的提高代码的可读性以及愉悦性,最起码看起来很舒服,不会出现多么痛的领悟!!! 可以得出结论
- 减少嵌套,代码看起来舒服很多
- 减少嵌套,可以减少思考,少掉头发
追求更少的嵌套,提前return
,但是不要过度哦~。
函数的默认参数 和 解构
在使用 JavaScript 时总是需要检查 null / undefined
值并分配默认值:
function test(animal, number) { if (!animal) return; const count = number || 1; // 如果没有提供 number 参数,则默认为 1 console.log(`${count}只${animal}!`); } // 测试结果 test('pig'); // 1 只 pig! test('pig', 2); // 2 只 pig!
我们可以通过分配默认函数参数来消除变量 count
,
function test(animal, number=1) { if (!animal) return; console.log(`${number}只${animal}!`); } // 测试结果 test('pig'); // 1 只 pig! test('pig', 2); // 2 只 pig!
如果我们的 animal
是一个 Object
对象怎么办? 我们可以指定默认参数吗? 答案是肯定的。
function test(animal) { // 如果有值,则打印 animal.name if (animal && animal.name) { console.log (animal.name); } else { console.log('what???'); } } //测试结果 test(undefined); // what??? test({ }); // what??? test({ name: 'pig', sex: 'boy' }); // pig
看看上面的例子,我们想要的是如果 animal.name
可用则打印水果名称,否则将打印 what??? 。 我们可以使用默认函数参数和解构(destructing
) 来避免animal && animal.name
这样的检查。
function test({name}={}) { console.log (name || 'what???'); } //测试结果 test(undefined); // what??? test({ }); // what??? test({ name: 'pig', sex: 'boy' }); // pig
由于我们只需要来自 animal
的 name
属性,我们可以使用 {name}
来解构参数,然后我们可以在代码中使用 name
作为变量来取代animal.name
。
我们还将空对象 {} 指定为默认值。 如果我们不这样做,你将在执行行测试时遇到test(undefined) – Cannot destructure property name of 'undefined' or 'null'.
(无法解析’undefined’
或’null’
的属性名称)。 因为 undefined
中 没有 name
属性。
Switch 语句真的好?
先来个例子吧,根据颜色打印对应的水果
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']
代码看起来是不是很冗长,有没有更好的写法呢?使用具有更清晰语法的 object
字面量试试吧。
// 使用对象字面量,根据颜色找出对应的水果 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(ES6)
引入的新的对象类型,允许您存储键值对。
更简单的写法
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); }
Array.every 和 Array.some 来处理条件语句
使用Javascript Array
函数可以有效的减少代码行,下面看代码:
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 }
结语
恰到好处的使用一些 coding 技巧,不但可以让你的Coding
速度与质量得到升华,而且可以起到无法估量的价值。毕竟让一个人快乐是无法用价值估量的,加油吧,骚年。
码云笔记 » 如何优雅的编写JavaScript(ES6)中的条件语句