在使用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 一些 更加简单方便的方法再添加。

function test14() {
const isAngRed = fruits.some(f => f.color == 'red');
console.log(isAngRed)
}
test14() // true

es6之更优雅的条件语句的更多相关文章

  1. 【译】写好JavaScript条件语句的5个技巧

    译文 当我们写JavaScript代码时,经常会用到到条件判断处理,这里有5个技巧能使你写出更好.更简洁的条件语句. 1.使用Array.includes处理多种条件 让我们来看一下的例子: // c ...

  2. JS 优化条件语句的5个技巧

    前言 在使用 JavaScript 的时候,有时我们会处理大量条件语句,这里有5个技巧帮助我们编写更简洁的条件语句. 一.对多个条件使用 Array.includes 例子: function con ...

  3. 优化 JS 条件语句的 5 个技巧

    优化 JS 条件语句的 5 个技巧 原创: 前端大全 前端大全 昨天 (给前端大全加星标,提升前端技能) 编译:伯乐在线/Mr.Dcheng http://blog.jobbole.com/11467 ...

  4. C#中一种替换switch语句更优雅的写法

    今天在项目中遇到了使用switch语句判断条件,但问题是条件比较多,大概有几十个条件,满屏幕的case判断,是否有更优雅的写法替代switch语句呢? 假设有这样的一个场景:商场经常会根据情况采取不同 ...

  5. 在用 JavaScript 工作时,我们经常和条件语句打交道,这里有5条让你写出更好/干净的条件语句的建议。

    1.多重判断时使用 Array.includes 2.更少的嵌套,尽早 return 3.使用默认参数和解构 4.倾向于遍历对象而不是 Switch 语句 5.对 所有/部分 判断使用 Array.e ...

  6. 写出更好的 JavaScript 条件语句

    1. 使用 Array.includes 来处理多重条件 // 条件语句 function test(fruit) { if (fruit == 'apple' || fruit == 'strawb ...

  7. JavaScript 复杂判断的更优雅写法

    我们编写js代码时经常遇到复杂逻辑判断的情况,通常大家可以用if/else或者switch来实现多个条件判断,但这样会有个问题,随着逻辑复杂度的增加,代码中的if/else/switch会变得越来越臃 ...

  8. JavaScript复杂判断的更优雅写法

    摘要: 写代码是一门艺术. 原文:JavaScript 复杂判断的更优雅写法 作者:Think. 公众号:大转转fe Fundebug经授权转载,版权归原作者所有. 前提 我们编写js代码时经常遇到复 ...

  9. 【转】转自微信公众号 JavaScript 复杂判断的更优雅写法

    与微信公众号看到一篇js复杂判断的文章,对我启发很大,故转到博客园以供后期不断学习并应用于项目.原文地址:https://mp.weixin.qq.com/s/ClFDRj4MnAxv1dJ5VWKS ...

随机推荐

  1. springboot中get post put delete 请求

    组合注解(RequestMapping的变形) @GetMapping = @RequestMapping(method = RequestMethod.GET) @PostMapping = @Re ...

  2. mysql in 查询参数化

    mysql查询语句where条件in mysql查询语句where条件in 正常情况需要查询的语句:select *from temp where id in ('1','2','3','4','5' ...

  3. java.io.EOFException ValueOperations.increment()操作后,获取值时有的bug

    ---恢复内容开始--- 今天使用spring-data-redis包操作redis,就是简单的使用redis的计数功能,在redis中的操作命令如:incr key;get key; 这两步操作使用 ...

  4. for break

    public static void main(String[] args) { aaa: for (int j = 0; j < 2; j++) { System.out.println(&q ...

  5. PythonStudy——函数的返回值 The return value of the function

    # 在函数体中,通过return关键词返回函数的内部数据给外部 """# 一.作用# return作用:1.结束函数:2.将函数的内部数据返回给外部 def fn(): ...

  6. centos7生产环境下openssh升级

    由于生产环境ssh版本太低,导致使用安全软件扫描时提示系统处于异常不安全的状态,主要原因是ssh漏洞.推荐通过升级ssh版本修复漏洞 因为是生产环境,所以有很多问题需要注意.为了保险起见,在生产环境下 ...

  7. django中多个app放入同一文件夹apps

    开发IDE:pycharm 新建一个apps文件夹 需要整理的app文件夹拖到同一个文件夹中,即apps.(弹出对话框,取消勾选Search for references) 在pycharm 中,右键 ...

  8. 新系统centos7重启网络报错

    场景: 在不知名云上新弄的centos7,改了IP之后启动不起来,使用systemctl status network查看结果如下:       排查过程:   1)NetworkManager是否关 ...

  9. 如何在Windows命令行(DOS界面)中调用 编译器 来编译C/C++源程序

    首先说明一下背景: 为什么要在DOS界面编译C/C++源程序?有很多现成的开发环境(IDE)如:vs, vc++等,这些开发环境集成了编译,调试,使用起来很方便,而且图形化操作界面,简洁明了.但是在开 ...

  10. WINDOWS NT操作系统的注册表文件

    WINDOWS NT操作系统的注册表文件 WINDOWS NT注册表文件分为系统文件和用户文件两类. 系统设置和缺少用户 配置数据存放在系统C:\Windows\System32\config文件夹下 ...