es6之更优雅的条件语句
在使用JavaScript时,条件判断是经常会用到的,一些简单的判断条件还可以接受,当遇到比较复杂多重条件时就比较恶心了。这里使用es6的小技巧使判断更优雅。
1、使用 Arrary.includes 处理多重条件(返回布尔值 true 或 false)
比如:
function test(fruit) {
if (fruit == "apple" || fruit == "orange") {
console.log("red");
} else {
console.log('blue')
}
}
当两个条件时,还比较简单,但是当条件增多这种写法就太麻烦了。可以使用如下:
function test2(fruit) {
const redFruits = ['apple', 'cherry', 'strawberry'];
if(redFruits.includes(fruit)) {
console.log('red')
} else {
console.log('blue')
}
}
将条件放到一个数组中,简便了好多。
2、少写嵌套,尽早返回
为之前的例子添加两个条件:
如果没有提供水果,抛出错误。
如果水果数量大于10,则打印。
function test3(fruit, quantity) {
const redFruits = ['apple', 'cherry', 'strawberry'];
if(!fruit) console.error('error');
if(redFruits.includes(fruit)) {
console.log('red');
if(quantity > 10) {
console.log('big quantity')
}
}
}
// test3(null)
// test3('apple')
test3('apple', 20)
test3
上面这个有问题,完全可以 写 并语句 && 。时刻记着 return 它可以阻止后面函数的执行。减少无必要的判断。
3、使用函数默认参数 和 解构
在JavaScript 中 我们经常需要检查 null 或 undefined 并赋予默认值。
function test4(fruit, quantity) {
if(!fruit) return;
const q = quantity || 0;
console.log(`we have ${q} ${fruit}!`)
}
test4('banana'); // we have 0 banana!
test4('apple', 3); // we have 3 apple!
事实上,我们可以通过函数的默认参数来去掉变量q
function test5(fruit, quantity = 1) {
if(!fruit) return;
const q = quantity || 0;
console.log(`we have ${quantity} ${fruit}!`)
}
test5('banana'); // we have 1 banana!
test5('apple', 3); // we have 3 apple!
注意:所有的函数参数都可以有默认值。
那如果fruit 是一个对象呢?如何使用默认值?
function test6(fruit) {
if(fruit && fruit.name) {
console.log(fruit.name);
} else {
console.log('unknown')
}
}
test6(undefined); // unknown
test6({ }); // unknown
test6({name: 'apple', color: 'red'}); // apple
上面是 当水果名字属性存在时,将其打印,否则打印 unknown。
我们可以通过默认参数 和 解构赋值的方法来避免 写出 fruit && fruit.name 这种条件。
// 解构 -- 只得到name属性。默认参数为空对象 {}
function test7({name} = {}) {
console.log(name || 'unknown');
}
test7(undefined); // unknown
test7({ }); // unknown
test7({name: 'apple', color: 'red'}); // apple
既然我们只需要fruit 的name属性,我们可以使用{name} 将其解构出来,之后在代码中就可以使用name代替fruit.name了。
我们还使用{}作为默认值,如果不使用默认值,当 undefined 时会报错。cannot destructure property name of 'undefined' or 'null'。
注意:解构 ---- 只适用于对象。
4、相比 switch 、Map / Object 也许是更好地选择。
如下我们想要根据颜色打印水果:
function test8(color) {
switch(color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
console.log(test8(null)); // []
console.log(test8(undefined)); // []
console.log(test8('red')); // [ 'apple', 'strawberry' ]
同样的结果可以通过对象字面量来实现,语法更简洁,如下:
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test9(color) {
return fruitColor[color] || [];
}
console.log(test9(null)); // []
console.log(test9(undefined)); // []
console.log(test9('red')); // [ 'apple', 'strawberry' ]
也可以使用Map来实现同样效果:
// 使用Map找到对应颜色的水果
const fruitColors = new Map().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);
function test10(color) {
return fruitColors.get(color) || [];
}
console.log(test10(null)); // []
console.log(test10(undefined)); // []
console.log(test10('red')); // [ 'apple', 'strawberry' ]
Map 是es6引入的新的对象类型,允许存放键值对。但是和json不一样,不能像 jsonObj.key 那样取值,会得到undefined。只能 mapObj.get(key) 取值。详细看Map。
还用一种 重构语法:
const fruits = [
{
name: 'apple',
color: 'red'
},
{
name: 'banana',
color: 'yellow'
},
{
name: 'grape',
color: 'purple'
},
{
name: 'orange',
color: 'yellow'
}
];
function test11(color) {
// 使用 Array.filter 方法
return fruits.filter(f => f.color == color)
}
console.log(test11('yellow')); // [ { name: 'banana', color: 'yellow' },{ name: 'orange', color: 'yellow' } ]
5、使用 Array.every 和 Array.some 来处理全部 / 部分满足条件:
如下代码是要检查是否所有水果都是红色的:
function test12() {
let isAllRed = true;
for(let f of fruits) {
if(!isAllRed) break;
isAllRed = (f.color == 'red');
}
console.log(isAllRed);
}
test12() // false
我们可以通过 Array.every 来减少代码量:
function test13() {
const isAllRed = fruits.every(f => f.color == 'red');
console.log(isAllRed);
}
test13() // false
类似的检查是否至少有一个是红色的,可以使用Array.some
function test14() {
const isAngRed = fruits.some(f => f.color == 'red');
console.log(isAngRed)
}
test14() // true
后续 es6 一些 更加简单方便的方法再添加。
es6之更优雅的条件语句的更多相关文章
- 【译】写好JavaScript条件语句的5个技巧
译文 当我们写JavaScript代码时,经常会用到到条件判断处理,这里有5个技巧能使你写出更好.更简洁的条件语句. 1.使用Array.includes处理多种条件 让我们来看一下的例子: // c ...
- JS 优化条件语句的5个技巧
前言 在使用 JavaScript 的时候,有时我们会处理大量条件语句,这里有5个技巧帮助我们编写更简洁的条件语句. 一.对多个条件使用 Array.includes 例子: function con ...
- 优化 JS 条件语句的 5 个技巧
优化 JS 条件语句的 5 个技巧 原创: 前端大全 前端大全 昨天 (给前端大全加星标,提升前端技能) 编译:伯乐在线/Mr.Dcheng http://blog.jobbole.com/11467 ...
- C#中一种替换switch语句更优雅的写法
今天在项目中遇到了使用switch语句判断条件,但问题是条件比较多,大概有几十个条件,满屏幕的case判断,是否有更优雅的写法替代switch语句呢? 假设有这样的一个场景:商场经常会根据情况采取不同 ...
- 在用 JavaScript 工作时,我们经常和条件语句打交道,这里有5条让你写出更好/干净的条件语句的建议。
1.多重判断时使用 Array.includes 2.更少的嵌套,尽早 return 3.使用默认参数和解构 4.倾向于遍历对象而不是 Switch 语句 5.对 所有/部分 判断使用 Array.e ...
- 写出更好的 JavaScript 条件语句
1. 使用 Array.includes 来处理多重条件 // 条件语句 function test(fruit) { if (fruit == 'apple' || fruit == 'strawb ...
- JavaScript 复杂判断的更优雅写法
我们编写js代码时经常遇到复杂逻辑判断的情况,通常大家可以用if/else或者switch来实现多个条件判断,但这样会有个问题,随着逻辑复杂度的增加,代码中的if/else/switch会变得越来越臃 ...
- JavaScript复杂判断的更优雅写法
摘要: 写代码是一门艺术. 原文:JavaScript 复杂判断的更优雅写法 作者:Think. 公众号:大转转fe Fundebug经授权转载,版权归原作者所有. 前提 我们编写js代码时经常遇到复 ...
- 【转】转自微信公众号 JavaScript 复杂判断的更优雅写法
与微信公众号看到一篇js复杂判断的文章,对我启发很大,故转到博客园以供后期不断学习并应用于项目.原文地址:https://mp.weixin.qq.com/s/ClFDRj4MnAxv1dJ5VWKS ...
随机推荐
- Flask+uwsgi+virtualenv环境配置
Linux系统版本: SLES12sp3 (阿里云) 1. 首先需要安装python-devel,否则后续安装会报错! rpm -qa|grep python-base 结果: python-base ...
- Github最简单实用的Git命令指南
create a new repository on the command line echo "# test" >> README.md git init gi ...
- 使用try和catch捕获异常
Java程序在执行过程中如果出现异常,会自动生成一个异常对象,该异常对象将被自动提交给JVM,当JVM接收到异常对象时,会寻找能处理这一异常的代码,并把当前异常对象交给其处理,这一过程称为捕获(cat ...
- CCF-20170903-JSON查询
这道题当时考ccf,五道题中做的时间最长的一道题....可惜最好只有0分!! 后来重现写了一下--(110行超级麻烦 主要思想:就是先对括号经行匹配,创建的时候分为创建表和创建元素两种情况,难点在于对 ...
- day01计算机基础
今日内容 1.计算机初步认识 1.计算机认识 1. 计算机基础 1.1硬件:cpu/内存/硬盘/主板/网卡 1.2操作系统 linux:免费开源 windows mac 1.3解释器/编译器 补充:编 ...
- 常见模块(四) os模块
注: os模块是实现python程序对操作系统(operation system)的操作 1.对文件或者目录进行删除或者创建的相关操作 # os.rename("b"," ...
- 19/03/15Pyhon笔记
1.快速在python中显示目标的2进制写法 bin(342) "0b101010110" 2.一个二进制位就是一比特(bit) 3.Python2默认无法识别中文,需要加文件头 ...
- 【SpringBoot】SpringBoot拦截器实战和 Servlet3.0自定义Filter、Listener
=================6.SpringBoot拦截器实战和 Servlet3.0自定义Filter.Listener ============ 1.深入SpringBoot2.x过滤器Fi ...
- eclipse配置环境变量
下载JDK:http://www.oracle.com/technetwork/java/javase/downloads/index.html 3.配置环境变量:右击“我的电脑”-->&quo ...
- UBUNTU中使用pip安装,提示cannt import main问题
在pip==8.1.1版本中,使用pip install Django==1.8.16时,提示 Traceback (most recent call last): File "/usr/ ...