JavaScript 编写更好的条件语句

在任何编程语言中,代码需要根据不同的条件在给定的输入中做不同的决定和执行相应的动作。

例如,在一个游戏中,如果玩家生命点为0,游戏结束。在天气应用中,如果在早上被查看,显示一个日出图片,如果是晚上,则显示星星和月亮。在这篇文章中,我们将探索JavaScript中所谓的条件语句如何工作。

如果你使用JavaScript工作,你将写很多包含条件调用的代码。条件调用可能初学很简单,但是还有比写一对对if/else更多的东西。这里有些编写更好更清晰的条件代码的有用提示。

  1. 数组方法 Array.includes

  2. 提前退出 / 提前返回

  3. 用对象字面量或Map替代Switch语句

  4. 默认参数和解构

  5. 用 Array.every & Array.some 匹配全部/部分内容

  6. 使用可选链和空值合并

1、数组方法 Array.includes

使用 Array.includes 进行多条件选择

例如:

function printAnimals(animal) {if (animal === 'dog' || animal === 'cat') {console.log(I have a ${animal});}
}console.log(printAnimals('dog')); // I have a dog

上面的代码看起来很好因为我们只检查了两个动物。然而,我们不确定用户输入。如果我们要检查任何其他动物呢?如果我们通过添加更多“或”语句来扩展,代码将变得难以维护和不清晰。

解决方案:

我们可以通过使用 Array.includes 来重写上面的条件

function printAnimals(animal) {const animals = ['dog', 'cat', 'hamster', 'turtle']; if (animals.includes(animal)) {console.log(I have a ${animal});}
}console.log(printAnimals('hamster')); // I have a hamster

这里,我们创建来一个动物数组,所以条件语句可以和代码的其余部分抽象分离出来。现在,如果我们想要检查任何其他动物,我们只需要添加一个新的数组项。

我们也能在这个函数作用域外部使用这个动物数组变量来在代码中的其他任意地方重用它。这是一个编写更清晰、易理解和维护的代码的方法,不是吗?

2、提前退出 / 提前返回

这是一个精简你的代码的非常酷的技巧。我记得当我开始专业工作时,我在第一天学习使用提前退出来编写条件。

让我们在之前的例子上添加更多的条件。用包含确定属性的对象替代简单字符串的动物。

现在的需求是:

  • 如果没有动物,抛出一个异常

  • 打印动物类型

  • 打印动物名字

  • 打印动物性别

const printAnimalDetails = animal => {let result; // declare a variable to store the final value// condition 1: check if animal has a valueif (animal) {// condition 2: check if animal has a type propertyif (animal.type) {// condition 3: check if animal has a name propertyif (animal.name) {// condition 4: check if animal has a gender propertyif (animal.gender) {result = ${animal.name} is a ${animal.gender} ${animal.type};;} else {result = "No animal gender";}} else {result = "No animal name";}} else {result = "No animal type";}} else {result = "No animal";}return result;
};console.log(printAnimalDetails()); // 'No animal'console.log(printAnimalDetails({ type: "dog", gender: "female" })); // 'No animal name'console.log(printAnimalDetails({ type: "dog", name: "Lucy" })); // 'No animal gender'console.log(printAnimalDetails({ type: "dog", name: "Lucy", gender: "female" })
); // 'Lucy is a female dog'

你觉得上面的代码怎么样?

它工作得很好,但是代码很长并且维护困难。如果不使用lint工具,找出闭合花括号在哪都会浪费很多时间。😄 想象如果代码有更复杂的逻辑会怎么样?大量的if..else语句。

我们能用三元运算符、&&条件等语法重构上面的功能,但让我们用多个返回语句编写更清晰的代码。

const printAnimalDetails = ({type, name, gender } = {}) => {if(!type) return 'No animal type';if(!name) return 'No animal name';if(!gender) return 'No animal gender';// Now in this line of code, we're sure that we have an animal with all //the three properties here.return ${name} is a ${gender} ${type};
}console.log(printAnimalDetails()); // 'No animal type'console.log(printAnimalDetails({ type: dog })); // 'No animal name'console.log(printAnimalDetails({ type: dog, gender: female })); // 'No animal name'console.log(printAnimalDetails({ type: dog, name: 'Lucy', gender: 'female' })); // 'Lucy is a female dog'

在这个重构过的版本中,也包含了解构和默认参数。默认参数确保如果我们传递undefined作为一个方法的参数,我们仍然有值可以解构,在这里它是一个空对象{}。

通常,在专业领域,代码被写在这两种方法之间。

另一个例子:

function printVegetablesWithQuantity(vegetable, quantity) {const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus'];// condition 1: vegetable should be presentif (vegetable) {// condition 2: must be one of the item from the listif (vegetables.includes(vegetable)) {console.log(I like ${vegetable});// condition 3: must be large quantityif (quantity >= 10) {console.log('I have bought a large quantity');}}} else {throw new Error('No vegetable from the list!');}
}printVegetablesWithQuantity(null); //  No vegetable from the list!
printVegetablesWithQuantity('cabbage'); // I like cabbage
printVegetablesWithQuantity('cabbage', 20); 
// 'I like cabbage
// 'I have bought a large quantity'

现在,我们有:

  • 1 if/else 语句过滤非法条件

  • 3 级嵌套if语句 (条件 1, 2, & 3)

一个普遍遵循的规则是:在非法条件匹配时提前退出。

function printVegetablesWithQuantity(vegetable, quantity) {const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus'];// condition 1: throw error earlyif (!vegetable) throw new Error('No vegetable from the list!');// condition 2: must be in the listif (vegetables.includes(vegetable)) {console.log(I like ${vegetable});// condition 3: must be a large quantityif (quantity >= 10) {console.log('I have bought a large quantity');}}
}

通过这么做,我们少了一个嵌套层级。当你有一个长的if语句时,这种代码风格特别好。

我们能通过条件倒置和提前返回,进一步减少嵌套的if语句。查看下面的条件2,观察我们是怎么做的

function printVegetablesWithQuantity(vegetable, quantity) {const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus'];if (!vegetable) throw new Error('No vegetable from the list!'); // condition 1: throw error earlyif (!vegetables.includes(vegetable)) return; // condition 2: return from the function is the vegetable is not in //  the list console.log(I like ${vegetable});// condition 3: must be a large quantityif (quantity >= 10) {console.log('I have bought a large quantity');}
}

通过倒置条件2,代码没有嵌套语句了。这种技术在我们有很多条件并且当任何特定条件不匹配时,我们想停止进一步处理的时候特别有用。

所以,总是关注更少的嵌套和提前返回,但也不要过度地使用。

3、用对象字面量或Map替代Switch语句

让我们来看看下面的例子,我们想要基于颜色打印水果:

function printFruits(color) {// use switch case to find fruits by colorswitch (color) {case 'red':return ['apple', 'strawberry'];case 'yellow':return ['banana', 'pineapple'];case 'purple':return ['grape', 'plum'];default:return [];}
}printFruits(null); // []
printFruits('yellow'); // ['banana', 'pineapple']

上面的代码没有错误,但是它仍然有些冗长。相同的功能能用对象字面量以更清晰的语法实现:

// use object literal to find fruits by colorconst fruitColor = {red: ['apple', 'strawberry'],yellow: ['banana', 'pineapple'],purple: ['grape', 'plum']};function printFruits(color) {return fruitColor[color] || [];
}

另外,你也能用 Map 来实现相同的功能:

// use Map to find fruits by colorconst fruitColor = new Map().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);function printFruits(color) {return fruitColor.get(color) || [];
}

Map 允许保存键值对,是自从ES2015以来可以使用的对象类型。

对于上面的例子,相同的功能也能用数组方法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 printFruits(color) {return fruits.filter(fruit => fruit.color === color);
}

4、默认参数和解构

当使用 JavaScript 工作时,我们总是需要检查 null/undefined 值并赋默认值,否则可能编译失败。

function printVegetablesWithQuantity(vegetable, quantity = 1) { 
// if quantity has no value, assign 1if (!vegetable) return;console.log(We have ${quantity} ${vegetable}!);
}//results
printVegetablesWithQuantity('cabbage'); // We have 1 cabbage!
printVegetablesWithQuantity('potato', 2); // We have 2 potato!

如果 vegetable 是一个对象呢?我们能赋一个默认参数吗?

function printVegetableName(vegetable) { if (vegetable && vegetable.name) {console.log (vegetable.name);} else {console.log('unknown');}
}printVegetableName(undefined); // unknown
printVegetableName({}); // unknown
printVegetableName({ name: 'cabbage', quantity: 2 }); // cabbage

在上面的例子中,如果vegetable 存在,我们想要打印 vegetable name, 否则打印"unknown"。

我们能通过使用默认参数和解构来避免条件语句 if (vegetable && vegetable.name) {} 。

// destructing - get name property only
// assign default empty object {}function printVegetableName({name} = {}) {console.log (name || 'unknown');
}printVegetableName(undefined); // unknown
printVegetableName({ }); // unknown
printVegetableName({ name: 'cabbage', quantity: 2 }); // cabbage

因为我们只需要 name 属性,所以我们可以使用 { name } 解构参数,然后我们就能在代码中使用 name 作为变量,而不是 vegetable.name 。

我们还赋了一个空对象 {} 作为默认值,因为当执行 printVegetableName(undefined) 时会得到一个错误:不能从 undefined 或 null 解构属性 name ,因为在 undefined 中没有 name 属性。

5、用 Array.every & Array.some 匹配全部/部分内容

我们能使用数组方法减少代码行。查看下面的代码,我们想要检查是否所有的水果都是红色的:

const fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function test() {let isAllRed = true;// condition: all fruits must be redfor (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() {// condition: short way, all fruits must be redconst 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() {// condition: if any fruit is redconst isAnyRed = fruits.some(f => f.color == 'red');console.log(isAnyRed); // true
}

6、使用可选链和空值合并

这有两个为编写更清晰的条件语句而即将成为 JavaScript 增强的功能。当写这篇文章时,它们还没有被完全支持,你需要使用 Babel 来编译。

可选链允许我们没有明确检查中间节点是否存在地处理 tree-like 结构,空值合并和可选链组合起来工作得很好,以确保为不存在的值赋一个默认值。

这有一个例子:

const car = {model: 'Fiesta',manufacturer: {name: 'Ford',address: {street: 'Some Street Name',number: '5555',state: 'USA'}}
} // to get the car model
const model = car && car.model || 'default model';// to get the manufacturer street
const street = car && car.manufacturer && car.manufacturer.address && 
car.manufacturer.address.street || 'default street';// request an un-existing property
const phoneNumber = car && car.manufacturer && car.manufacturer.address 
&& car.manufacturer.phoneNumber;console.log(model) // 'Fiesta'
console.log(street) // 'Some Street Name'
console.log(phoneNumber) // undefined

所以,如果我们想要打印是否车辆生产商来自美国,代码将看起来像这样:

const isManufacturerFromUSA = () => {if(car && car.manufacturer && car.manufacturer.address && car.manufacturer.address.state === 'USA') {console.log('true');}
}checkCarManufacturerState() // 'true'

你能清晰地看到当有一个更复杂的对象结构时,这能变得多乱。有一些第三方的库有它们自己的函数,像 lodash 或 idx。例如 lodash 有 _.get 方法。然而,JavaScript 语言本身被引入这个特性是非常酷的。

这展示了这些新特性如何工作:

// to get the car model
const model = car?.model ?? 'default model';// to get the manufacturer street
const street = car?.manufacturer?.address?.street ?? 'default street';// to check if the car manufacturer is from the USA
const isManufacturerFromUSA = () => {if(car?.manufacturer?.address?.state === 'USA') {console.log('true');}
}

这看起来很美观并容易维护。它已经到 TC39 stage 3 阶段,让我们等待它获得批准,然后我们就能无处不在地看到这难以置信的语法的使用。

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/62146.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

400电话号码怎么开通

开通400电话是企业提供客户服务的重要步骤。下面是一些步骤和注意事项,帮助您顺利开通400电话。 第一步:选择400电话服务提供商 选择一家可靠的400电话服务提供商非常重要。您可以通过搜索引擎、咨询行业内人士或者参考其他企业的经验来选择合适的服务提…

【LeetCode75】第四十题 最大层内元素和

目录 题目: 示例: 分析: 代码: 题目: 示例: 分析: 这道题和LeetCode75的上一题大同小异,都是要我们对二叉树进行层序遍历。 那具体如何层序遍历我再上一题也详细介绍过了&#…

尚硅谷SpringMVC (1-4)

一、SpringMVC简介 1、什么是MVC MVC 是一种软件架构的思想,将软件按照模型、视图、控制器来划分 M : Model ,模型层,指工程中的 JavaBean ,作用是处理数据 JavaBean 分为两类: 一类称为实体类Bean&am…

Linux配置ADSL链接

在Linux中配置ADSL链接,可以按照以下步骤进行: 安装rp-pppoeconf工具,这个工具可以通过终端窗口使用。运行命令“rp-pppoeconf”来配置ADSL链接。终端窗口会显示一个向导模式,用于配置ADSL链接。输入用户名和密码。这些信息是用来…

Flux语言 -- InfluxDB笔记二

1. 基础概念理解 1.1 语序和MySQL不一样,像净水一样通过管道一层层过滤 1.2 不同版本FluxDB的语法也不太一样 2. 基本表达式 import "array" s 10 * 3 // 浮点型只能与浮点型进行运算 s1 9.0 / 3.0 s2 10.0 % 3.0 // 等于 1 s3 10.0 ^ 3.0 // 等于…

【附源码】Python-3.9.5安装教程

软件下载 软件:Python版本:3.9.5语言:英文大小:26.9M安装环境:Win11/Win10/Win8/Win7硬件要求:CPU2.5GHz 内存2G(或更高)下载通道①百度网盘丨64位下载链接:https://pan.baidu.com/…

李宏毅 2022机器学习 HW2 strong baseline 上分路线

strong baseline上分路线 baseline增加concat_nframes (提升明显)增加batchnormalization 和 dropout增加hidden layer宽度至512 (提升明显) 提交文件命名规则为 prediction_{concat_nframes}[{n_hidden_layers}{dropout}_bn].c…

vue3渲染函数h的简单使用——定义局部组件

vue3渲染函数h的简单使用 基本用法 创建 Vnodes Vue 提供了一个 h() 函数用于创建 vnodes: import { h } from vueconst vnode h(div, // type{ id: foo, class: bar }, // props[/* children */] )更多用法 详情查看官方文档 在SFC中定义局部组件使用 h函数…

21.3 CSS 背景属性

1. 背景颜色 background-color属性: 设置元素的背景颜色. 它可以接受各种颜色值, 包括命名颜色, 十六进制颜色码, RGB值, HSL值等.快捷键: bctab background-color:#fff;<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"…

Flowable7 设计器

1、flowable7 已经在主版本上移除了Flowable UI相关的包&#xff0c;包含bpm-json相关的所有包和流程设计器相关前端文件。 2、flowable7 版本目前只保留了xml运行相关的包&#xff0c;ui modeler已经移除 3、目前官方给的回复是只能在 flowable 云产品上使用设计器&#xff…

Educational Codeforces Round 154 (Rated for Div. 2)

Educational Codeforces Round 154 (Rated for Div. 2) A. Prime Deletion 思路&#xff1a; 因为1到9每个数字都有&#xff0c;所以随便判断也质素即可 代码 #include<bits/stdc.h> using namespace std; #define int long long #define rep(i,a,n) for(int ia;i<…

HP惠普星15青春版/惠普小欧笔记本电脑15s-du1008tx原装出厂Win11系统

适用型号&#xff1a;15s-du1007tx、15s-du1008tx、15s-du1009tx、15s-du1010tx、15s-du1011tx、15s-du1012tx、15s-du1013tx 自带所有驱动、出厂主题壁纸LOGO、Office办公软件、惠普电脑管家等预装程序 所需要工具&#xff1a;32G或以上的U盘 文件格式&#xff1a;ISO 文件大…

thinkphp6 入门(3)--获取GET、POST请求的参数值

一、Request对象 thinkphp提供了Request对象&#xff0c;其可以 支持对全局输入变量的检测、获取和安全过滤 支持获取包括$_GET、$_POST、$_REQUEST、$_SERVER、$_SESSION、$_COOKIE、$_ENV等系统变量&#xff0c;以及文件上传信息 具体参考&#xff1a;https://www.kanclou…

搭配购买——并查集+01背包

Joe觉得云朵很美&#xff0c;决定去山上的商店买一些云朵。 商店里有 n 朵云&#xff0c;云朵被编号为 1,2,…,n&#xff0c;并且每朵云都有一个价值。但是商店老板跟他说&#xff0c;一些云朵要搭配来买才好&#xff0c;所以买一朵云则与这朵云有搭配的云都要买。但是Joe的钱有…

【问题】你知道帕累托原则吗?作为一名项目管理人员你是如何将帕累托原则应用在你的项目管理中的?

又是一个我遇到过的非典型的面试问题&#xff08;当时面试架构的时候问到&#xff09;&#xff0c;估计是因为自己提到过做过项目管理工作&#xff0c;所以想试探一下我这边究竟有没有了解过项目管理的理论知识吧。记得当时我回答得不算太好&#xff0c;没有贴合这个主题&#…

YOLOV5/YOLOV7/YOLOV8改进:用于低分辨率图像和小物体的新 CNN 模块SPD-Conv

1.该文章属于YOLOV5/YOLOV7/YOLOV8改进专栏,包含大量的改进方式,主要以2023年的最新文章和2022年的文章提出改进方式。 2.提供更加详细的改进方法,如将注意力机制添加到网络的不同位置,便于做实验,也可以当做论文的创新点。 3.涨点效果:SPD-Conv提升小目标识别,实现有效…

uniapp小程序位置信息配置

uniapp 小程序获取当前位置信息报错 报错信息&#xff1a; getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json 需要在manifest.json配置文件中进行配置&#xff1a;

Tomcat安装及配置教程-Windows和Linux

本文主要介绍Windows版本Tomcat部署的详细步骤和列出Linux部署的简要细节命令,其中Windows从一到七,Linux用第八个标题讲述 一,安装 1,打开官网,https://tomcat.apache.org/,选择Tomcat 8.5.93版本,点击Download,根据系统版本选择压缩包 2,下载完毕,将压缩包解压,将所有文件放…

泛型的学习

泛型深入 泛型&#xff1a;可以在编译阶段约束操作的数据类型&#xff0c;并进行检查 泛型的格式&#xff1a;<数据类型> 注意&#xff1a;泛型只能支持引用数据类型 //没有泛型的时候&#xff0c;集合如何存储数据//如果我们没有给集合指定类型&#xff0c;默认认为…

MyBatis——MyBatis插件原理

摘要 本博文主要介绍MyBatis插件机原理&#xff0c;帮助大家更好的理解和学习MyBatis。 一、插件机制概述 MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下&#xff0c;MyBatis允许使用插件来拦截的方法调用包括&#xff1a; Executor (update, que…