1、使用Object.keys快速获取对象键名
let obj = {
a: 1,
b: 2
}
// bad
let keys = []
for (value in obj) {
keys.push(value)
}
// good
let keys = Object.keys(obj) // ['a', 'b']
2、解构数组进行变量值的替换
// bad
let a = 1,
b = 2
let temp = a
a = b
b = temp
// good
let a = 1,
b = 2
[b, a] = [a, b]
3、解构对象
// bad
setForm (person) {
this.name = person.name
this.age = person.age
}
// good
setForm ({name, age}) {
this.name = name
this.age = age
}
4、解构时重命名简化命名
// bad
setForm (data) {
this.one = data.aaa_bbb_ccc_ddd
this.two = data.eee_fff_ggg
}
// good
setForm ({aaa_bbb_ccc_ddd, eee_fff_ggg}) {
this.one = aaa_bbb_ccc_ddd
this.two = eee_fff_ggg
}
// best
setForm ({aaa_bbb_ccc_ddd: one, eee_fff_ggg: two}) {
this.one = one
this.two = two
}
5、解构时设置默认值
// bad
setForm ({name, age}) {
if (!age) age = 16
this.name = name
this.age = age
}
// good
setForm ({name, age = 16}) {
this.name = name
this.age = age
}
6、||短路符设置默认值
let person = {
name: '张三',
age: 38
}
let name = person.name || '佚名'
7、&&短路符判断依赖的键是否存在防止报错’xxx of undfined’
let person = {
name: '张三',
age: 38,
children: {
name: '张小三'
}
}
let childrenName = person.children && person.childre.name
8、字符串拼接使用${}
let person = {
name: 'LiMing',
age: 18
}
// bad
function sayHi (obj) {
console.log('大家好,我叫' + person.name = ',我今年' + person.age + '了')
}
// good
function sayHi (person) {
console.log(`大家好,我叫${person.name},我今年${person.age}了`)
}
// best
function sayHi ({name, age}) {
console.log(`大家好,我叫${name},我今年${age}了`)
}
9、函数使用箭头函数
let arr [18, 19, 20, 21, 22]
// bad
function findStudentByAge (arr, age) {
return arr.filter(function (num) {
return num === age
})
}
// good
let findStudentByAge = (arr, age)=> arr.filter(num => num === age)
10、函数参数校验
// bad
let findStudentByAge = (arr, age) => {
if (!age) throw new Error('参数不能为空')
return arr.filter(num => num === age)
}
// good
let checkoutType = () => {
throw new Error('参数不能为空')
}
let findStudentByAge = (arr, age = checkoutType()) =>
arr.filter(num => num === age)
评论区