一、简洁的语法
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'