JS代码技巧(一)

一、简洁的语法

ES6提供了许多很好的语法可以让前端分开发者编写的代码更加清晰可读,同时使业务逻辑更加清晰明了。

1、代码里避免写绝对路径,尽量使用相对路径

例如:

const url = 'http://aaaaa.com:8000/app/xxx'

替换为:

const url = 'app/xxx'

 而域名则改为在项目配置文件中进行统一配置,可以很大程度上避免因为环境切换引起的未知bug

2、使用箭头函数,简化代码

例如:

const idList = dataSource.map(function(i) {
   return i.id
})

替换为:

const idList = dataSource.map(i => i.id)

3、使用模板字符串代替字符串

例如:

const person = 'My name is : ' + userName + '(' + age + ')'

 替换为:

const person = `My name is : ${userName}(${age})`

 4、解构赋值、设置变量默认值

例1:

const userList = res.list
const total = res.total || 0

替换为:

const { list: userList, total = 0} = res

例2:

const start = time[0]
const end = time[1]

替换为:

const [start, end] = time

 例3:

const tempList = list.slice()
const newObj = Object.assign({}, obj, {value: 'xx'})

 替换为:

const tempList = [...list]
const newObj = {...obj, value: 'xx'}

4、使用promise、async/await简化代码结构

例如:

ajax.post(url)
.done(function(res1) {
  ajax.post(res1.nextUrl)
  .done(function(res2) {
    // do something
  })
})

 替换为:

getRes1()
.then(res1 => getRes2(res1.nextUrl))
.then(res2 => {
  // do something
})

// 或者

const res1 = await getRes1()
const res2 = await getRes2(res1.nextUrl)

二、使用声明式语句代替命令式语句

例1:

// 命令式
const tempList = []
for(let item of list) {
  if(item.sex === 'male') {
    tempList.push(item.useName)
  }
}
return tempList

// 申明式
return (
  list
  .filter(item => item.sex === 'male')
  .map(i => i.useName)
)

例2:

// 命令式
const hasUserName = false
for(let user of users) {
  if(!user.userName) {
    hasUserName = true
    break
  }
}

// 申明式
return (
  users.some(user => !user.userName)
)

例3:

// 命令式
const item = {id: 1, name: 'zhangsan', age: 12}
const list = [
  {id: 1, name: 'zhangsan', age: 14},
  {id: 2, name: 'lisi', age: 16},
  {id: 3, name: 'wangwu', age: 18}
]
const itemIndex = list.findIndex(i => i.id === item.id)
if(tempIndex !== -1) {
  list.split(itemIndex, 1)
} else {
  list.push(item)
}
return list


// 申明式
return (
  list.some(i => i.id === item.id)
    ? list.filter(i => i.id !== item.id)
    : [...list, item]
)

三、避免多重嵌套 

1、条件嵌套 

例1:

const res = ''
if(type === 'A') {
  res = 'a'
} else if(type === 'B') {
  res = 'b'
} else {
  res = 'defaultValue'
}
return res

替换为:

const typeMap = {
  'A': 'a',
  'B': 'b',
  'C': 'c'
}

return typeMap[type] || 'defaultValue'

例2:

const res = ''
if(conA) {
  if(conB) {
    res = 'ab'
  } else {
    res = 'ac'
  }
} else if(conF) {
  res = 'f'
} else {
  res = 'dafaultValue'
}
return res

替换为:

if(conA && conB) return 'ab'
if(conB) return 'ac'
if(conF) return 'f'
return 'defaultValue'

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值