写出更好的 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. 少写嵌套,尽早返回
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 {
throw new Error('No fruit!');
}
}
// 测试结果
test(null); // 报错:No fruits
test('apple'); // 打印:red
test('apple', 20); // 打印:red,big quantity
/_ 当发现无效条件时尽早返回 _/
function test(fruit, quantity) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (!fruit) throw new Error('No fruit!'); // 条件 1:尽早抛出错误
if (!redFruits.includes(fruit)) return; // 条件 2:当 fruit 不是红色的时候,直接返回
console.log('red');
// 条件 3:必须是大量存在
if (quantity > 10) {
console.log('big quantity');
}
}
3. 相较于 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 = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']); function test(color) {
return fruitColor.get(color) || [];
}
map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。
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);
}
4. 使用 Array.every 和 Array.some 来处理全部/部分满足条件
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
}
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
}
本文参考掘金大佬Hopsken!
map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。
写出更好的 JavaScript 条件语句的更多相关文章
- 在用 JavaScript 工作时,我们经常和条件语句打交道,这里有5条让你写出更好/干净的条件语句的建议。
1.多重判断时使用 Array.includes 2.更少的嵌套,尽早 return 3.使用默认参数和解构 4.倾向于遍历对象而不是 Switch 语句 5.对 所有/部分 判断使用 Array.e ...
- [label][翻译][JavaScript-Translation]七个步骤让你写出更好的JavaScript代码
7 steps to better JavaScript 原文链接: http://www.creativebloq.com/netmag/7-steps-better-javascript-5141 ...
- 【译】写好JavaScript条件语句的5个技巧
译文 当我们写JavaScript代码时,经常会用到到条件判断处理,这里有5个技巧能使你写出更好.更简洁的条件语句. 1.使用Array.includes处理多种条件 让我们来看一下的例子: // c ...
- 使用Groovy+Spock轻松写出更简洁的单测
当无法避免做一件事时,那就让它变得更简单. 概述 单测是规范的软件开发流程中的必不可少的环节之一.再伟大的程序员也难以避免自己不犯错,不写出有BUG的程序.单测就是用来检测BUG的.Java阵营中,J ...
- JavaScript条件语句4--分支语句--if
JavaScript条件语句--分支语句 学习目标 1.掌握条件语句if 2.掌握prompt()的应用 3.掌握alert的应用 If语句 语法一: If(condition){ statement ...
- JavaScript条件语句-5--if语句的嵌套
JavaScript条件语句 学习目标 1.掌握length属性的应用 2.掌握if语句的嵌套 length 语法:string.length 功能:获取string字符串的长度 返回值:number ...
- 如何在 ASP.NET Core 中写出更干净的 Controller
你可以遵循一些最佳实践来写出更干净的 Controller,一般我们称这种方法写出来的 Controller 为瘦Controller,瘦 Controller 的好处在于拥有更少的代码,更加单一的职 ...
- JavaScript -- 条件语句和循环语句
if语句 在我们开发程序的时候,经常会遇到选择题,例如,年龄大于18,你就可以抽烟喝酒烫头,年龄小于18,你就只能吃饭喝水.在我们的代码中,我们可以用if语句来实现这种判断 语法一: if( cond ...
- JavaScript 条件语句
if语句 有些代码块只能在一定条件下运行,通过if.if else.else代码块,可以让你的代码按条件执行. // 控制流 var foo = true; var bar = false; ...
随机推荐
- 基于虚拟机的centos6.5 搭建本地光盘yum源
在线yum安装必须要保持服务器能够连入网络并且他下载的还会比较慢因为地址大部分多是国外的下载站.另外yum在线下载的都是比较新的软件包,可能不是很稳定,那么使用yum的本地资源就是光盘里的RPM包,让 ...
- Linux有几种安装软件的方式?????
看了Windows后台软件安装的过程,想必Linux也是这样.拿RHEL7来打比方 最开始Linux上安装软件只提供源代码,需要自己去编译源代码,拷贝库文件等 RPM 红帽软件包管理器可以自动地执行上 ...
- PAT 1146 Topological Order
This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topol ...
- codechef营养题 第三弹
第三弾が始まる! codechef problems 第三弹 一.Motorbike Racing 题面 It's time for the annual exciting Motorbike Rac ...
- Thinkphp 批量更新方法 saveALL
批量更新只适用于一个字段的更新,原理是用自定义函数拼接sql语句,然后再执行sql语句. //数据 $data[] = array('id'=>1,'value'=>value1); $d ...
- 洛谷 P1877 BZOJ 2748 cogs 791 [HAOI2012]音量调节
题目描述 一个吉他手准备参加一场演出.他不喜欢在演出时始终使用同一个音量,所以他决定每一首歌之前他都需要改变一次音量.在演出开始之前,他已经做好一个列表,里面写着每首歌开始之前他想要改变的音量是多少. ...
- Codeforces Round #219 (Div. 2) D题
D. Counting Rectangles is Fun time limit per test 4 seconds memory limit per test 256 megabytes inpu ...
- NOIP2010 提高组合集
NOIP 2010 提高组合集 T1 机器翻译 模拟题,用一个栈模拟,桶记录即可. #include <iostream> #include <cstdio> #include ...
- HDU——1267 下沙的沙子有几粒?
下沙的沙子有几粒? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total ...
- MYSQL的一些常用函数
#数学函数 SELECT ABS(-8);#绝对值SELECT CEILING(9.8);#查询大于等于给定数值的最小整数SELECT FLOOR(9.8);#查询小于等于给定数值的最大整数SELEC ...