每周分享常用编程技巧与规范(前端)

使用对象代替 if 及 switch 的简单赋值逻辑

场景:根据不同会员等级用户给予不同的折扣

  • 旧方案 使用if 或者 switch进行不同等级会员赋予不同折扣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let userRank = '白银会员'
let discount = 9.8

// 数据多我就switch
switch(userRank){
case '白银会员':
discount = 9.8
break
case '黄金会员':
discount = 9.5
break
case '钻石会员':
discount = 9.3
break
}
// 数据少我就if判断
if (userRank === '白银会员'){
discount = 9.8
}else if(userRank === '黄金会员'){
discount = 9.5
}else if(userRank === '钻石会员'){
discount = 9.3
}
  • 新方案 采用对象的方式,适合简单判断赋值情况。相对于之前的方案,代码量少,而且更加清晰。
1
2
3
4
5
6
7
8
let userRank = '白银会员'
let discountObj = {
'白银会员': 9.8,
'黄金会员': 9.5,
'钻石会员': 9.3
}

let discount = discountObj[userRank] || 9.8

三元与短路操作

场景:判断会员等级是否是‘钻石’,如果是给予高等级客服待遇,实际使用最多的场景为判断后台返回数据中某个字段是否有值,没有着赋予一个默认值。

  • 旧代码 if 循环
1
2
3
4
let priority = 'low'
if(userRank === '钻石会员'){
priority = 'hight'
}
  • 新代码 短路操作
1
2
3
4
// 过滤数据
let userRank = data.userRank || '白银会员'
// 三目运算
(urserRank === '钻石会员')?priority = 'hight':priority = 'low'

使用双位运算符~~

场景:代替正数的floor(),与负数的ceil(),整体来说就是浮点数只保留整数部分

1
2
3
4
5
6
// 9
Math.floor(9.9)
~~9.9
// -9
Math.celi(-9.9)
~~-9.9
You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×