20条示例代码让你的代码更简洁

9 篇文章 2 订阅

图片

1.通过条件判断给变量赋值布尔值的正确姿势
// bad
if (a === 'a') {
    b = true
} else {
    b = false
}

// good
b = a === 'a'


2.在if中判断数组长度不为零的正确姿势
// bad
if (arr.length !== 0) {
    // todo
}

// good
if (arr.length) {
    // todo
}


3.同理,在if中判断数组长度为零的正确姿势
// bad
if (arr.length === 0) {
    // todo
}

// good
if (!arr.length) {
    // todo
}


4.简单的if判断使用三元表达式
// bad
if (a === 'a') {
    b = a
} else {
    b = c
}

// good
b = a === 'a' ? a : c


5.使用includes简化if判断
// bad
if (a === 1 || a === 2 || a === 3 || a === 4) {
    // todo
}

// good
let arr = [1, 2, 3, 4]
if (arr.includes(a)) {
    // todo
}


巧用数组方法,尽量避免用for循环

6.使用some方法判断是否有满足条件的元素
// bad
let arr = [1, 3, 5, 7]
function isHasNum (n) {
    for (let i = 0; i < arr.length; i ++) {
        if (arr[i] === n) {
            return true
        }
    }
    return false
}

// good
let arr = [1, 3, 5, 7]
let isHasNum = n => arr.some(num => num === n)

// best
let arr = [1, 3, 5, 7]
let isHasNum = (n, arr) => arr.some(num => num === n)


7.使用forEach方法遍历数组,不形成新数组
// bad
for (let i = 0; i < arr.length; i ++) {
    // todo
    arr[i].key = balabala
}

// good
arr.forEach(item => {
    // todo
    item.key = balabala
})


8.使用filter方法过滤原数组,形成新数组
// bad
let arr = [1, 3, 5, 7],
    newArr = []
for (let i = 0; i < arr.length; i ++) {
    if (arr[i] > 4) {
        newArr.push(arr[i])
    }
}

// good
let arr = [1, 3, 5, 7]
let newArr = arr.filter(n => n > 4) // [5, 7]


9.使用map对数组中所有元素批量处理,形成新数组
// bad
let arr = [1, 3, 5, 7],
    newArr = []
for (let i = 0; i < arr.length; i ++) {
    newArr.push(arr[i] + 1)
}

// good
let arr = [1, 3, 5, 7]
let newArr = arr.map(n => n + 1) // [2, 4, 6, 8]


巧用对象方法,避免使用for…in

10.使用Object.values快速获取对象键值
let obj = {
    a: 1,
    b: 2
}
// bad
let values = []
for (key in obj) {
    values.push(obj[key])
}

// good
let values = Object.values(obj) // [1, 2]


11.使用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']


巧用解构简化代码

12.解构数组进行变量值的替换
// bad
let a = 1,
    b = 2
let temp = a
a = b
b = temp

// good
let a = 1,
    b = 2
[b, a] = [a, b]


13.解构对象
// bad
setForm (person) {
    this.name = person.name
    this.age = person.age 
}

// good
setForm ({name, age}) {
    this.name = name
    this.age = age 
}


14.解构时重命名简化命名

有的后端返回的键名特别长,你可以这样干

// 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
}


15.解构时设置默认值
// 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 
}


16.||短路符设置默认值
let person = {
    name: '张三',
    age: 38
}

let name = person.name || '佚名'


17.&&短路符判断依赖的键是否存在防止报错’xxx of undfined’
let person = {
    name: '张三',
    age: 38,
    children: {
        name: '张小三'
    }
}

let childrenName = person.children && person.childre.name


18.字符串拼接使用${}
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}了`)
}


19.函数使用箭头函数
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)


20.函数参数校验
// 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)


欢迎大佬们指正交流,感谢支持

图片

点击下方卡片/微信搜索,关注公众号“天宇文创意乐派”(ID:gh_cc865e4c536b)

听说点赞和关注本号的都找到漂亮的小姐姐了哟且年后必入百万呀!!

往期推荐

[

再见 Swagger UI!国人开源了一款超好用的 API 文档生成框架,Star 4.7K+,真香!!

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247488219&idx=2&sn=36e5232ac6a75c2df040fec508bbefe0&chksm=ebb6f1b8dcc178aee371f4325cbb7f6493173d14fef22f9b4e6a741914c264a19715c59b26a1&scene=21#wechat_redirect)

[

JavaScript 细节和一些实际应用,了解一下

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247487814&idx=2&sn=2e2b761acf87f8550cad528795141727&chksm=ebb6f225dcc17b33dfd7bec5e2f8ee5dd75211d4a29e37f9c05ea1052ca7cf6fed0a0123795f&scene=21#wechat_redirect)

[

sparrow-js开源低代码场景化工作台,自动给你生成代码

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247487682&idx=2&sn=26d15f07ffccf6454c6aa08c04e00230&chksm=ebb6f3a1dcc17ab7973d3844f15161bcbec19c7ef85a32ce0ae590dd96df76a5d3b6327e3097&scene=21#wechat_redirect)

[

nvm安装与使用

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247487379&idx=1&sn=fb06b04c517731e2ec2b2baa43635a9f&chksm=ebb6ecf0dcc165e6ef1c9b889a3f42ede75c84f9c3b8359d9e39587aed6c1534f7119631e316&scene=21#wechat_redirect)

[

前端代码优化,以及日常使用技巧

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247487682&idx=4&sn=7dc9a838847145f31ebfb2a8cca46960&chksm=ebb6f3a1dcc17ab7e58fc1a20f60843e3ff656c066f22fc616f9ecf5adbc1dce8baa5523cfae&scene=21#wechat_redirect)

[

一键生成UI小姐姐的设计稿,开发效率提升100%

](http://mp.weixin.qq.com/s?__biz=MzI4MDQ5MTUzMg==&mid=2247487088&idx=3&sn=e977dc4c7a2b5e681bd621b20023caaf&chksm=ebb6ed13dcc164056f688f7c4fd2cfc4ed045bec27049efc2c75c01189dcb992ee61c781098a&scene=21#wechat_redirect)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值