1、类型判断、转换
- 1
- 2
- 3
- 4
- 5
if (visibleFlag) {
visible = 1;
} else {
visible = 0;
}
改为(如:在数据库保存时无法自动转换数据类型):
- 1
visible = visibleFlag + 0
2、独立函数调用
- 1
postTitle = postTitle ? postTitle.trim() : '';
改为:
- 1
postTitle = util.trim(xss.sanitize(postTitle))
3、多条件合并为一个:转为数组的include等操作
- 1
if (action === 'create' || action === 'edit') {...}
改为:
- 1
if (['create', 'edit'].includes(action)) {...}
4、空值判断简化
- 1
if (page !== undefined && page !== ''){...}
改为
- 1
if (!page) {...}
5、嵌套if简化
- 1
- 2
- 3
- 4
- 5
if (x) {
if (y) {...} else {...}
} else {
...
}
改为:
- 1
if (x && y) {...} else {...}
6、复杂if改为使用正则(通配符)
如:
- 1
if (/^1[34578]\d{9}$/i.test(phone)) {...}
7、重复判断剥离并复用:赋值给变量、常量,减少二次判断
- 1
- 2
- 3
if (postStatus === 'draft' || postStatus === 'auto-draft') {...}
...
if (postStatus === 'draft' || postStatus === 'auto-draft') {...} else {...}
改为:
- 1
- 2
const postDraft = postStatus === 'draft' || postStatus === 'auto-draft';
if (postDraft) {...}
8、关联表查询、子查询改为视图查询
参考: