[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
想成为一名优秀的开发者,除了高超的技术水平,一手优雅规范的代码更是能锦上添花。
那么什么样的代码才算得上规范,什么样的代码才能让人眼前一亮,对你刮目相看呢?
1. 健壮性
1.1 参数问题
参数类型判断
使用函数的入参时,先判断参数的类型是否符合预期;
参数保底
后续操作需要某个参数,但是并没有传入这个参数,可在函数中定义一个保底数据(也就是默认值)
如:
function add1(a,b) { return a+b; } function add2(a, b=20) { return a + b; }
add1(10); // NaN add2(10); // 30
add1中a=10, b=undefined,10 + undefined
得出NaN的结果,而add2中因为给b提供了默认值20,当add2传入第二个参数时,b会被重新赋值,否则使用默认值20。
上边的add2还可以写成
function add2(a,b) { b = b || 20; // b没传,就用20 return a + b; }
参数为某个构造函数实例
使用 instanceof 去判断参数是否为某个特定构造函数的实例
1.2 易错代码
请求的响应回调中前端总要根据后端返回数据处理逻辑,但万一后端返回了一些意料之外的东西,很有可能造成代码报错,可使用 try-catch 捕获错误,
2. 可读性
简单明了,可读性高的代码,不仅会让协同开发的人员一看就懂,后期自己维护的时候也能快速定位问题,
2.1 语义化
开发时,可以打开谷歌翻译,使用简单易懂的英文给变量、方法等命名。
2.2 命名规范
常量-全大写
普通变量-小写驼峰(名词)
普通方法 -小写驼峰(动词)
类或者构造函数-首字母大写
局部变量- 下划线(_)开头
2.3 结构清晰
避免回调嵌套,优先使用promise等
3. 可复用性
局部层面:减少代码重复,逻辑复用,提取公共代码;
全局层面:创建公用模板
4. 可扩展性
模块分明
高内聚,低耦合