当前位置:网站首页>Alternative writing of if else in a project
Alternative writing of if else in a project
2022-06-29 07:21:00 【You are far from it.】
What dare you write more than one in the project if else Judgment is not afraid of being killed ?
Exceed or equal to in the project 3 individual if else If you judge , This kind of writing is unfriendly .
There is such a requirement in the project , Switch between different options , Show different data .
Normal writing , Namely if else Determine the index value of the switch , Then show different data We will use multiple layers if else, This kind of writing can be used to judge within two , Multi level judgment , Code readability is still poor
// Data to show
let data = []
// Suppose this is the data of catering
let cateringData = [1,2,3]
// Suppose this is traffic data
let trafficData = [1,2,3]
// Suppose this is the data of the hotel
let hotelData = [1,2,3]
// We should reject this kind of writing
if (index === 0) {
data = cateringData
} else if(index === 1) {
data = trafficData
} else if(index === 2) {
data = hotelData
}
The following way of writing may be better , This is similar to the strategy pattern
Some people will think that this kind of writing , There seems to be more code , This idea is wrong .
I like what a teacher said :
If the code is written for , To better show the hierarchy of data , Extra code is necessary
// Data to show
let data = []
// Suppose this is the data of catering
let cateringData = [1,2,3]
// Suppose this is traffic data
let trafficData = [1,2,3]
// Suppose this is the data of the hotel
let hotelData = [1,2,3]
// Use this way of writing
let mapData = [
{
id: 0,
desc: ' Catering data ',
fn: () => cateringData
},
{
id: 1,
desc: ' Traffic data ',
fn: () => trafficData
},
{
id: 2,
desc: ' Hotel data ',
fn: () => hotelData
}
]
function changeIndex(index) {
data = mapData [index].fn()
}

tip: There's another one about arrays , Encountered in the project , Next time , You can write it down . It's a little hard .
边栏推荐
猜你喜欢

关于数据库,你应该知道的事情

Message queue avoiding repeated refund by idempotent design and atomic lock

关联性——相关性分析

Domestic code hosting center code cloud

反射修改final

JDBC connects to the database and socket sends the client.

电子商务盛行,怎么提高商店转换率?

IDEA 集成 码云

Error: GPG check FAILED Once install MySQL

Do you really understand "binder copy once"?
随机推荐
uva10635
Qt 串口编程
QT foreach keyword
Redis of NoSQL database (I): Installation & Introduction
E-commerce is popular, how to improve the store conversion rate?
RPC and RMI
The meaning and calculation method of receptive field
Solve the problem that NPM does not have permission
Exploring the depth of objects in JVM series
虚拟DOM真的是最快的吗?
服装行业的CRM品牌供应商如何选型?
Markdown 技能树(9):表格
电子商务盛行,怎么提高商店转换率?
[software test] interface - Basic test process
uva11825
Qt STL类型迭代器
Database - Synonyms
微信小程序学习笔记(暑假)
Save token get token refresh token send header header
多模态 —— Learnable pooling with Context Gating for video classification