JS Elegance (JS Code Optimization Tips)

This article has participated in the "Newcomer Creation Ceremony" event to start the road to gold creation.

write in front

It’s another year of graduation season, and I sigh in my spare time. I vaguely remember that because I was too young, I didn’t have good coding habits and didn’t pay attention to coding efficiency, and I worked overtime frequently during the internship stage. Today, I took the time to summarize a few Programming optimization tips, as a reference for young cuties who are about to enter the front-end club, seniors should review it, and welcome everyone to add corrections!

JS Code Optimization Tips

Serial if optimization

In many businesses, many branches are often involved. When there are too many branches, we can easily write if-else-if into a very ugly code segment like code_1. So what are the optimization methods? Let's take a look see code

code-1 unoptimized code

The logic is very simple, return the corresponding color according to the code

// code-1
// 未优化前代码
function getColor(code){
  if(code === '200'){
    return 'blue-blue'
  }else if(code === '201'){
    return 'green-green'
  }else if(code === '202'){
    return 'red-red'
  }else{
    return 'other-other'
  }
}
console.log(getColor('200'))
复制代码

code-2 uses switch optimization

It can be seen that the number of lines of code after using switch optimization has not been reduced, but the structure has been optimized, the code looks more comfortable, and the reading is relatively simpler, and this is not our optimal choice

// code-2
// 使用 switch 优化
function getColor2(code){
  switch(code){
    case '200':
      return 'blue-blue'
      break
    case '201':
      return 'green-green'
      break
    case '202':
      return 'red-red'
      break
    default:
      return 'other-other'
      break
  }
}
console.log(getColor2('200'))
复制代码

code-3 uses map optimization

Obviously, using the mapping-optimized code, the code size is reduced without affecting the readability of the code. For more complex branches, the mapping method will have more obvious advantages, and there is another advantage in doing so, If the branch is very complex, the mapping can be extracted and introduced into the code as a json file to further optimize the code and make it easier to maintain

// code-3
// 使用映射优化 
function getColor3(code){
  var colorMap = {
    '200': 'blue-blue',
    '201': 'green-green',
    '202': 'red-red',
  }
  return colorMap[code] || 'other-other'
}
console.log(getColor3('200'))
复制代码

Optional chaining operator ?.

As the name implies, optional means that when the read attribute is referenced as null ( null or  undefined), it will not cause an error, such as code-1. When we cannot determine the data structure of req, then if we want to get the type, It needs to be obtained through the chain operation req.data.params.type, and any failure to obtain req, data, params will cause an error, so it needs to be judged one by one through the && symbol

if(req && req.data && req.data.params && req.data.params.type === '200'){}
复制代码

use ?. optimize

It can be seen that after using ?., the simplicity of the code and the increase in rubbing! !

if(req?.data?.params?.type === '200'){}
复制代码

Merge objects

Merging objects can be said to be a very common logic in business. There are mainly two optimized ways of writing.

未优化代码

通过逐一赋值的方式合并,这种方式非常 ugly,随着 key 值越多,代码 ugly 的程度会急剧增加

let info = {
  name: 'yimwu',
  tel: '134xxxxx320'
}
let otherInfo = {
  name: 'yimwu',
  age: '18',
  address: 'gd'
}
info.age = otherInfo.age
info.address = otherInfo.address
console.log(info)
复制代码

通过扩展运算符优化

let info = {
  name: 'yimwu',
  tel: '134xxxxx320'
}
let otherInfo = {
  name: 'yimwu',
  age: '18',
  address: 'gd'
}
info = {...info, ...otherInfo}
console.log(info)
复制代码

通过 ES6 方法 Object.assign() 优化

let info = {
  name: 'yimwu',
  tel: '134xxxxx320'
}
let otherInfo = {
  name: 'yimwu',
  age: '18',
  address: 'gd'
}
Object.assign(info, otherInfo)
console.log(info)
复制代码

深拷贝

我们都知道对象存在引用,当我们想将一个对象的所有内容赋值给另外一个对象时,如果只是简单的用 “ = ”赋值,两个对象将共享一块内存,也就是说两个对象指向同一个内存块的引用,那么之后改变任何一个对象中的值,两个对象都会同步改变,这并不是我们想要的,因此,在对象赋值时我们需要进行深拷贝,对对象进行拷贝赋值,保证两个对象指向不同的内存块,这样才能保证对象的修改不会互相影响

未优化代码

深拷贝传统的写法需要对对象进行深度遍历,每个对象的 key 逐个赋值

function deepClone(obj) {
  if (typeof obj != 'object') return obj;
  var temp = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
          if (obj[key] && typeof obj[key] == 'object') {
              temp[key] = deepClone(obj[key])
          } else {
              temp[key] = obj[key];
          }
      }
  }
  return temp;
}
let info = {
  name: 'yimwu',
  tel: '134xxxxx320',
  address: {
    home: 'jy',
    company: 'gz'
  }
}

let infoCopy = deepClone(info)

复制代码

通过 JSON 方法优化

通过 JSON.parse 和 JSON.stringify 巧妙地将对象转化成字符串再进行解析,js 将重新赋值到新的内存块中,达到深拷贝的效果

let info = {
  name: 'yimwu',
  tel: '134xxxxx320',
  address: {
    home: 'jy',
    company: 'gz'
  }
}

let infoCopy = JSON.parse(JSON.stringify(info))
复制代码

写在最后

今天抽空就先写这么几点,后续继续补充其他相关的优化小Tip,欢迎各位评论区补充,指正!
博主接下来将持续更新好文,欢迎关注博主哟!!
如果文章对您有帮助麻烦亲点赞、收藏 + 关注和博主一起成长哟!!❤❤❤

Guess you like

Origin juejin.im/post/7102809229878099976