在使用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. some learning

    一.windows下迁移access到mysql Windows下 Access 数据 迁移到 Mysql(5.5)数据库 . 具体做法 . 在access的表中选择,文件->导出->保存 ...

  2. HTTP 各状态码大全

    基本涵盖了所有问题 HTTP 400 – 请求无效 HTTP 401.1 – 未授权:登录失败 HTTP 401.2 – 未授权:服务器配置问题导致登录失败 HTTP 401.3 – ACL 禁止访问 ...

  3. 将文本转化为Numpy的矩阵

    def file2matrix(filename): fr = open(filename) numberOfLines = len(fr.readlines()) #get the number o ...

  4. Eclipse 使用 VS Emulator for android 调试环境配置 步骤

    模拟器启动器地址:C:\Program Files (x86)\Microsoft Emulator Manager\1.0\emulatorcmd.exe 获取模拟器ID命令:emulatorcmd ...

  5. C#通过代码判断并注册程序集到GAC

    var dllName = "EasyHook.dll"; var dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirec ...

  6. MySQL Error--The Table is full

    问题描述 在MySQL 错误日志中发下以下错误信息:[ERROR] /export/servers/mysql/bin/mysqld: The table '#sql-xxxx-xxx' is ful ...

  7. zombodb 得分以及高光

    得分以及高光在搜索引擎中有很重要的作用 得分zdb.score 使用方法 zdb.score(tid) 参考示例 SELECT zdb.score(ctid), * FROM products WHE ...

  8. python的set处理二维数组转一维数组

    for splitValue in set(dataset[:, featureIndex].tolist()): 首先set是一个无序,无重复的数据结构,所以很多时候使用它来进行去重:但是set接收 ...

  9. hadoop完全分步式搭建

    实验环境介绍 4台机器,规划如下: 计算机名 IP地址 角色 master 192.168.138.200 NameNode,SecondaryNameNode,ResourceManager sla ...

  10. centos7启动过程及systemd详细说明

    开机启过程 POST->BOOT SEQUENCE-> BOOTLOADER->KERNEL + INITRAMFS(INITRD)->ROOTFS->/sbin/ini ...