javaScript-条件语句优化
1、多重判断时使用 Array.includes
test = (fruit: string) => {
if (fruit == 'apple' || fruit == 'strawberry'....) {
console.log('apple or strawberry');
}
}
test = (fruit: string) => {
const fruits = ['strawberry','apple'];
if (fruits.includes(fruit)) {
console.log('apple or strawberry');
}
}
2、使用默认参数和解构
在JavaScript中我们总是需要检查 null / undefined的值和指定默认值:
test = (fruit: string, quantity?: any) => {
if (!fruit) {
return;
}
console.log(quantity || 0)
}
我们可以通过声明 默认函数参数
test = (fruit: string, quantity: any = 20) => {
if (!fruit) {
return;
}
console.log(quantity)
}
test = (fruit?: any) => {
if (fruit && fruit.name) {
console.log(fruit.name)
} else {
console.log('unknown')
}
}
通过默认参数以及解构从而避免判断条件 fruit && fruit.name
test = ({ name }: any = {}) => {
console.log(name || 'name unknown')
}
我们也需要声明空对象 {} 作为默认值。如果我们不这么做,当执行 test(undefined) 时,你将得到一个无法对 undefined 或 null 解构的的错误。因为在 undefined 中没有 name 属性。
也可以使用lodash的_.get()方法减少对null的检查
3、倾向于对象遍历而不是Switch语句
test = (color: string) => {
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
在这种场景,我们可以用对象遍历实现相同的结果,语法看起来更简洁:
test = (color: string) => {
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
return fruitColor[color] ||[]
}
4、对 所有/部分 判断使用Array.every & Array.some
利用 JavaScript Array 的内置方法来减少代码行数。看下面的代码,我们想要检查是否所有水果都是红色:
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'grape', color: 'purple' }
];
test = (fruits: any = []) => {
let isAllRed: boolean = true;
// 条件:所有水果都是红色
for (let f of fruits) {
if (!isAllRed) break;
isAllRed = (f.color == 'red');
}
}
test9 = (fruits: any = []) => {
console.log(fruits.every((item: any) => item.color === 'red'))
}
test10 = (fruits: any = []) => {
console.log(fruits.some((item: any) => item.color === 'red'))
}
5、更少的嵌套,尽早 Return
例子:
如果没有传入参数 fruit,抛出错误
接受 quantity 参数,并且在 quantity 大于 10 时打印出来
test = (fruit: any, quantity: any) => {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1: fruit 必须有值
if (fruit) {
// 条件 2: 必须是red的
if (redFruits.includes(fruit)) {
console.log('red');
// 条件 3: quantity大于10
if (quantity > 10) {
console.log('big quantity');
}
}
} else {
throw new Error('No fruit!');
}
}
当发现无效语句时,尽早Return
test = (fruit: any, quantity: any) => {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
// 条件 1: fruit 必须有值
if (!fruit) {
throw new Error('No fruit!');
return;
}
// 条件 2: 必须是red的
if (redFruits.includes(fruit)) {
console.log('red');
// 条件 3: quantity大于10
if (quantity > 10) {
console.log('big quantity');
}
}
}
javaScript-条件语句优化的更多相关文章
- JavaScript条件语句-5--if语句的嵌套
JavaScript条件语句 学习目标 1.掌握length属性的应用 2.掌握if语句的嵌套 length 语法:string.length 功能:获取string字符串的长度 返回值:number ...
- JavaScript条件语句4--分支语句--if
JavaScript条件语句--分支语句 学习目标 1.掌握条件语句if 2.掌握prompt()的应用 3.掌握alert的应用 If语句 语法一: If(condition){ statement ...
- 【译】写好JavaScript条件语句的5个技巧
译文 当我们写JavaScript代码时,经常会用到到条件判断处理,这里有5个技巧能使你写出更好.更简洁的条件语句. 1.使用Array.includes处理多种条件 让我们来看一下的例子: // c ...
- JavaScript 条件语句
if语句 有些代码块只能在一定条件下运行,通过if.if else.else代码块,可以让你的代码按条件执行. // 控制流 var foo = true; var bar = false; ...
- javascript条件语句
//条件语句 if (false) { console.log("is true") } else { console.log("is false") } // ...
- JavaScript -- 条件语句和循环语句
if语句 在我们开发程序的时候,经常会遇到选择题,例如,年龄大于18,你就可以抽烟喝酒烫头,年龄小于18,你就只能吃饭喝水.在我们的代码中,我们可以用if语句来实现这种判断 语法一: if( cond ...
- 写出更好的 JavaScript 条件语句
1. 使用 Array.includes 来处理多重条件 // 条件语句 function test(fruit) { if (fruit == 'apple' || fruit == 'strawb ...
- JS条件语句优化
1.对多个条件使用Array.includes eg: function test(fruit){ ...
- js - 总结一下条件语句优化
[笔记] // 简单的语句用三目运算符也可以的(除了需要return的) 1 == 1 ? console.log('执行了...1') : console.log(); 1 == 2 ? conso ...
- 【代码笔记】Web-JavaScript-JavaScript 条件语句
一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
随机推荐
- mongo distinct 指定条件
db.Article.distinct("字段名称",{"Comment.Reply.email" : "xxx"})
- android学习四---Activity和Intent
1.android项目资源深入了解 在深入学习android之前,先好好玩玩手机上的应用,大部分程序都有一个图标,点开图标,程序启动,一定时间后,程序会跳转到第一个界面,比如手机QQ,点开图标,会跳出 ...
- const,var,let区别(转载)
1.const定义的变量不可以修改,而且必须初始化. const b = 2;//正确 // const b;//错误,必须初始化 console.log('函数外const定义b:' + b);// ...
- Kattis - wheretolive 【数学--求质心】
Kattis - wheretolive [数学] Description Moving to a new town can be difficult. Finding a good place to ...
- HihoCoder - 1339 Dice Possibility(概率dp)
题意:求用N(1<=N<=100)个骰子掷出M(1<=M<=600)的概率 分析:直接求概率可能出现6^100次方,会爆精度.可以用一个数组dp[i][j]记录用i个骰子掷出j ...
- 整合subeclipse和Tortoise SVN
先来一个下载链接(subeclipse1.8和TortoiseSVN1.7): http://download.csdn.net/detail/cangfengluyu/8416395 对于同 ...
- SVN使用—概念及生命周期
一.SVN简介 Apache Subversion 通常被缩写成 SVN,是一个开放源代码的版本控制系统,Subversion 在 2000 年由 CollabNet Inc 开发,现在发展成为 Ap ...
- jQuery垂直手风琴菜单 菜单项带小图标
在线演示 本地下载
- C\C++与Java中的static关键字
C\C++里面的static: 面向过程的static: 在c和c++面向过程的设计里,在全局变量前加上static关键字则可将该变量定义为一个静态全局变量,比如: static int a; 那么c ...
- error: 'for' loop initial declarations are only allowed in C99 mode
error: 'for' loop initial declarations are only allowed in C99 mode 出现错误: error: 'for' loop initia ...