美文网首页
如何编写简洁高效的js代码

如何编写简洁高效的js代码

作者: jia林 | 来源:发表于2022-01-26 22:15 被阅读0次

作为开发,谁都不想维护乱糟糟的代码(if else 一大堆)。良好的编码看起来赏心悦目,避免产生更多的bug,今天分享下我日常的编码技巧。

1.避免 if 过长

  • 如果判断值满足多个条件,我们可能会这么写:
if(type === 'view' || type === 'edit' || type === 'get' ) { .... }
  • 优化改造
// 使用includes,扩展性也高
if(['view','edit','get'].includes(type)) { ... }

2.给对象添加属性

  • 场景
const map = { type:'view'}
if(value) {
  map.name = 'jialin'
}
  
  • 优化改造
  const map = { type:'view',...(value && { name:'jialin'})}

3.判断不为null、不为undefined、不为 ""

  • 场景
if(price !== null || price !== '' || price !== undefined) { ... }
  • 优化改造
if((price ?? ' ')!=='') { ... }

4.避免过多的if判断

  • 场景
if(type === 'view') {
....
}else if(type === 'edit') {
....
}
  • 优化改造
switch(type) {
  case 'view':
      ...
      break;
  case 'edit':
     ...
     breal;
  default:
     ...
}

5.条件简写

  • 场景
if(value) {  getList() }
  • 优化改造
value && getList()

6.可选项(?)

  • 有时我们需要判断对象里的某些属性是否存在,在进行处理,不然会报错
const obj = { 
  a: { b: {  c: 5 } } 
}
if (!!obj.a && !!obj.a.b && !!obj.a.b.c) { ... }
  • 优化改造
if (!!toto.a?.b?.c) { ... }

其他

  • 字符串模板
  • ...扩展运算符
  • 解构赋值

ES6及以上提供了很多方便操作的api,像startsWidth()、endsWidth()、padStart()等,大家在项目当中多多实践哦!

相关文章

网友评论

      本文标题:如何编写简洁高效的js代码

      本文链接:https://www.haomeiwen.com/subject/admnhrtx.html