jser必会的技巧,让你的代码更容易维护

72 阅读1分钟

1、避免使用过多的或运算符

例如:

      const status = 3
      if (status === 1 || status === 2 || status === 3) {
        console.log('满足条件')
      }

推荐:

      const status = '3'
      if ([1, 2, 3].includes(+status)) {
        console.log('满足条件')
      }

2、重复代码提取为函数,进行复用

例如:

      if (user.role === 'admin') {
        const data = {
          name: user.name,
          age: user.age,
          sex: user.sex,
          phone: user.phone
        }
        save(data)
      }

      if (use.role === 'manager') {
        const data = {
          name: user.name,
          age: user.age,
          sex: user.sex,
          phone: user.phone
        }
        save(data)
      }

推荐:

      const getData = user => {
        const data = {
          name: user.name,
          age: user.age,
          sex: user.sex,
          phone: user.phone
        }
        return data
      }

      if (['admin', 'manager'].includes(user.role)) {
        const data = getData(user)
        save(data)
      }

3、使用对象传参,使参数易维护

例如:

      const createUser = (name, age, sex, phone) => {
        // ...
      }

推荐:

      const createUser = ({name, age, sex, phone}) => {
        // ...
      }

4、使用return替代过多的if判断

例如:

      const getBool = obj => {
        if (obj.isValid) {
          if (obj.isBool) {
            return true
          } else {
            return false
          }
        } else {
          return false
        }
      }
      console.log('getBool', getBool({ isValid: false, isBool: true }))

推荐:

      const getBool = obj => {
        if (!obj.isValid) return false
        if (!obj.isBool) return false
        return true
      }

5、使用枚举替代魔术字符串

例如:

      if (status === 'success') {
        //
      } else if (status === 'wraning') {
        //
      } else if (status === 'error') {
        //
      }

像这种判断,时间久了,没有注释说明,其他人员可能不好分别含义。

推荐(将不同的状态放到一个对象中统一维护,一来避免拼写错误,二来后续维护时更快地梳理逻辑):

      const statusMap = {
        SUCCESS: 'success',
        WARNING: 'wraning',
        ERROR: 'error'
      }
      if (status === statusMap.SUCCESS) {
        //
      } else if (status === statusMap.WARNING) {
        //
      } else if (status === statusMap.ERROR) {
        //
      }

6、使用可选链简化空值处理

为了避免因属性不存在而导致的报错,我们可能会使用&&,但使用?.可以使代码看起来更简洁

例如:

      const response = {
        data: {
          user: {
            name: '小王'
          }
        }
      }
      const name = response && response.data && response.data.user && response.data.user.name
      console.log('name', name)

推荐:

      const name = response?.data?.user?.name

7、使用纯函数提高代码可维护性

例如:

推荐:

image.png