当前位置:网站首页>The way of code neatness -- hit the pain point directly
The way of code neatness -- hit the pain point directly
2022-07-25 10:09:00 【A cabbage~】
all 2022 了 , No, no one else can't use es6 Well , No, no, no, No
Hit the pain point
Pain points 1:if else Straight to the top
When you take over a new project developed by others , There are always pages
if (xxx) { // What to do } else if (xxx) { // What to do } else if (xxx) { // What to do } else if (xxx) { // What to do } else if (xxx) { // What to do } else if (xxx) { // What to do } else if (xxx) { // What to do } else { // What to do }A big lump , I'm a code purist , It's hard to watch
Optimization plan 1:switch
switch (status){
case xxx:
// What to do
break
case xxx2:
case xxx3:
// What to do
break
case xxx:
// What to do
break
case xxx:
// What to do
break
default:
// What to do
break
}
Be careful :case xxx2andcase xxx3The logic is exactly the same , This can be omittedExecute statementandbreak, thencase xxx2Automatic execution ofcase xxx3The logic of .
Optimization plan 2:Object
const typeObj = {
'xxx1': ' It can be a string value ',
'xxx2': [' It can be an array value 1',' It can be an array value 2'],
'xxx3': {
a: ' It can be object value ' },
'xxx4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function },
'default': 'xxx'
}
const status = ' state - Corresponding typeObj Properties of '
const typeVal = typeObj[status] || typeObj['default']
Be careful :holdJudge the conditionAsThe property name of the object, takeProcessing logicAsProperty value of object, While performing the operation , adoptObject property lookupIn the way oflogic, This kind of writing is especially suitable for the case of monistic condition judgment .
How to write the judgment of multiple conditions ??? People don't talk much and go directly to the code .
// multivariate if else nesting
if (type === 'aaa') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
} else if (type === 'bbb') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
}
// Optimize the writing
const typeObj = {
'aaa1': ' It can be a string value ',
'aaa2': [' It can be an array value 1',' It can be an array value 2'],
'aaa3': {
a: ' It can be object value ' },
'aaa4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function },
'bbb1': ' It can be a string value ',
'bbb2': [' It can be an array value 1',' It can be an array value 2'],
'bbb3': {
a: ' It can be object value ' },
'bbb4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function },
'default': 'xxx'
}
const text = 'aaa/bbb',
const num = ' state - Corresponding 1、2、3、4'
const typeVal = typeObj[`${
text}${
num}`] || typeObj['default']
There are many bb A mouthful … You can skip this note directly
In the use of JSON.parse(JSON.stringify(xxx)) We should pay attention to a few points when :
JSON.parse(JSON.stringify()) Copy time object 、Error object 、 Regular expressions , function , perhaps undefined equivalence , This method will cause problems
1. If json There are time objects in it , Then the serialization result : Time object => String form ;
2. If json Are there in RegExp、Error object , The result of serialization will only get empty objects RegExp、Error => {};
3. If json Are there in function,undefined, The result of serialization will function,undefined The loss of ;
4. If json Are there in NaN、Infinity and -Infinity, The result of serialization will be null;
5. If json There are objects in that are generated by constructors , The result of serialization will discard the constructor;
6. If there is a circular reference in the object, deep copy cannot be realized
Optimization plan 3:Map ( Finally I can write es6 了 , Giant chicken jelly )
I do not know! ES6-Map Read my previous article es6 Set and Map data structure
and Object The way is very similar , It's all in the form of key value pairs
const typeMap = new Map([
['xxx1': ' It can be a string value '],
['xxx2': [' It can be an array value 1',' It can be an array value 2']],
['xxx3': {
a: ' It can be object value ' }],
['xxx4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function }],
['default': 'xxx']
])
const status = ' state - Corresponding typeMap Key '
const typeVal = typeMap.get(status) || typeMap.get('default')
Map Multiple judgments and Object It's written in a similar way
// multivariate if else nesting
if (type === 'aaa') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
} else if (type === 'bbb') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
}
// Optimize the writing
const typeMap = new Map([
['aaa1': ' It can be a string value '],
['aaa2': [' It can be an array value 1',' It can be an array value 2']],
['aaa3': {
a: ' It can be object value ' }],
['aaa4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function }],
['bbb1': ' It can be a string value '],
['bbb2': [' It can be an array value 1',' It can be an array value 2']],
['bbb3': {
a: ' It can be object value ' }],
['bbb4': () => {
// It can be a callback function to do something , You can write ordinary function, Use here es6 Arrow function }],
'default': 'xxx'
]
const text = 'aaa/bbb',
const num = ' state - Corresponding 1、2、3、4'
const typeVal = typeMap.get(`${
text}${
num}`) || typeMap.get('default')
There are more here bb A mouthful …
MapObjects andObjectWhat's the difference between objects ?
- Objects have their own prototypes , So there is always one object prototype key .
- The key of an object can only be character string perhaps Symbols, But a Map The key to this can be Any value .
- Map It can be used Any kind of The data for key
- Map adopt size Property to get the number of key value pairs , The key value pair of the object can pass Object.keys()、Object.values() To get the corresponding array .
If you feel Query criteria Piece together character string It's a bit awkward ?? Don't panic , There are more ways than difficulties , There's another way : Use Map, And then use Object As key, Not much bb, Go straight to the code
// multivariate if else nesting
if (type === 'aaa') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
} else if (type === 'bbb') {
if (status === 1) {
// What to do }
if (status === 2) {
// What to do }
if (status === 3) {
// What to do }
if (status === 4) {
// What to do }
}
const typeMap = new Map([
[{
type: 'aaa', status: 1}, () => {
// What to do }],
[{
type: 'aaa', status: 2}, () => {
// What to do }],
[{
type: 'aaa', status: 3}, () => {
// What to do }],
[{
type: 'aaa', status: 4}, () => {
// What to do }],
[{
type: 'bbb', status: 1}, () => {
// What to do }],
[{
type: 'bbb', status: 2}, () => {
// What to do }],
....... Get it. ,get It's too wordy to stop writing at the bottom
])
const text = 'aaa/bbb',
const num = ' state - Corresponding 1、2、3、4' // Don't worry about it status Value is number ,num and status It's not equal , I just explained, so I didn't write the corresponding value ( Please make a detour , Walk slowly !!!)
const typeVal = [...typeMap].filter(([key, val]) => key.type === text && key.status === num))[0][1]()
If there are many more conditions , There are many conditions to do the same thing , Then you can only use Regular 了
const typeMap = new Map([
[/^aaa[1-4]$/, () => {
// What to do }],
[/^bbb[1-3]$/, () => {
// What to do }],
[/^bbb4$/, () => {
// What to do }],
....... Get it. ,get Is that it
])
const text = 'aaa/bbb',
const num = ' state - Corresponding 1、2、3、4' // Don't worry about it status Value is number ,num and status It's not equal , I just explained, so I didn't write the corresponding value ( Please make a detour , Walk slowly !!!)
const typeVal = [...typeMap].filter(([key, val]) => key.test(`${
text}${
num}`)))[0][1]()
Pain points 2: Judge some uncertain values
Optimization plan 1: ?? Null merge operator
You may have met , If a variable is empty , When it needs to be assigned a default value . We usually write like this :
const num = number || 1
however , The above code will have a bug. If number The value of is 0, It will be regarded as unable to get its value , Will take to ' Can't get ' This string .
If you want to do this , Before that, we can only use ternary operators to realize :
const num = (number !== undefined) ? number : 1
Now you can use ?? 了 , It only works if the value to the left of the operator is null perhaps undefined When , Will take the value on the right of the operator :
const num = number ?? 1
There are many bb A word of …
Logical assignment operator ??=、&&=、 ||=
// Equate to a = a || b
a ||= b;
// Equate to c = c && d
c &&= d;
// Equate to e = e ?? f
e ??= f;
When we want to get the background interface json data , But what the background says and what attributes do not necessarily exist , There is uncertainty , Then our front-end code is written into a lump …
// Omit here ajax request , Too lazy to write , This thing should be able to write
.....
// Suppose the interface returns json The data is res
const res = {
code: 200,
data: {
userInfo: {
},
options: {
id: 1,
title: '',
url: ''
}
},
message: 'success'
}
// Then here we will use options The content of
// But the interface in the background is very spicy say options May not exist perhaps options Inside title May not exist
// At this time, our code can only Write a lump if Judge the condition
eg:
if(res.data && res.data.options && res.data.options.title) {
// What to do
If the data hierarchy is nested more ...... We will res.data && res.data.options && res.data.options.title && ......
It's very speechless .......
}
When we need to try to access properties or methods in an object and are not sure whether the object exists
eg: xxx Suppose it's a div The box , I want to access its width
const xWidth = xxx ? xxx.width : ''
There are other scenes that will encounter similar problems , Here are just two of the most common .
Optimization plan 2:?. Optional link operator
We usually judge whether an object has a certain attribute !==undefined、in Operator 、hasOwnProperty()、propertyIsEnumerable()
Here we use es6 Newly added ?. Operator :
?. Chain judgment operation
?. Operator , Judge directly in the chain call , Whether the object on the left isnullorundefined. If yes, , It's not going to go down , It's going back to undefined.
Common usage scenarios :
- Attribute access : You need to get the attributes in an object
a?.b a?.[c] In the above code , If a by undefined or null, The expression will immediately return undefined, Otherwise, return the value of the accessed property . in other words , They are equivalent to the following code : a == null ? undefined : a.b a == null ? undefined : a[c]- Method call : When trying to call a method , You can also use
a?.() The same is if a by undefined or null, Then return to undefined, Otherwise, the method will be called . But what needs extra attention is , This operator does not judge a Whether it is a function type , So if a Is a value of another type , Then this code will still throw exceptions at runtime .- Access deep-seated properties : When accessing the deeper level properties of an object , It can also be used in series
Some people may be too lazy to judge whether it is really necessary , Add this operator to each attribute in the access link . But like the code above shows , This kind of code is not readable . And if there really is an object that should exist because of some bug Cause it doesn't exist , Then you should throw an exception when accessing it , In this way, problems can be found in time , Instead of making it hidden . It is recommended to use the optional chain operator only when necessary .a?.b?.[0]?.()?.d
const res = {
code: 200,
data: {
userInfo: {
},
options: {
id: 1,
title: '',
url: ''
}
},
message: 'success'
}
// ?. Use
if(res?.data?.options?.title) {
// What to do
}
I'll add later , To be continued ???
边栏推荐
- MLX90640 红外热成像仪测温模块开发说明
- Is binary cross entropy really suitable for multi label classification?
- [tensorflow2 installation] tensorflow2.3-cpu installation pit avoidance guide!!!
- Terminal definition and wiring of bsp3 power monitor (power monitor)
- 无线振弦采集仪参数配置工具的设置
- App lifecycle and appledelegate, scenedelegate
- 手持振弦采集仪对振弦传感器激励方法和激励电压
- 工程仪器振弦传感器无线采集仪的采集数据发送方式及在线监测系统
- TensorFlow raw_ RNN - implement the seq2seq mode to take the output of the previous time as the input of the next time
- Subtotal of rospy odometry sinkhole
猜你喜欢

小程序调起微信支付

Qt 6.2的下载和安装

ADC简介

Temperature, humidity and light intensity acquisition based on smart cloud platform

【建议收藏】靠着这些学习方法,我入职了世界五百强——互联网时代的“奇技淫巧”

【近万字干货】别让你的简历配不上你的才华——手把手教你制作最适合你的简历

MLX90640 红外热成像传感器测温模块开发笔记(三)

多通道振弦、温度、模拟传感信号采集仪数据查看和参数修改

Introduction to low power consumption and UPF

TM1638 LED数码显示模块ARDUINO驱动代码
随机推荐
LOAM 融合 IMU 细节之 TransformToEnd 函数
Mlx90640 infrared thermal imager temperature measurement module development notes (4)
ISP图像信号处理
Loam transformtoend function integrating IMU details
CCF 201509-2 date calculation
CCF 201604-2 Tetris
VCS常用命令
用ESP32+TM1638实验NTP网络校时闹钟的ARDUINO代码
Armv8 datasheet learning
Camera attitude estimation
无线中继采集仪的常见问题
线程池的设计和原理
TensorFlow raw_ RNN - implement the seq2seq mode to take the output of the previous time as the input of the next time
FPGA basic advanced
一.初始MySQL,MySQL安装、配置环境、初始化
An ASP code that can return to the previous page and automatically refresh the page
MLX90640 红外热成像传感器测温模块开发笔记(二)
salt常见问题
小程序H5获取手机号方案
LoRA转4G及网关中继器工作原理