JavaScript优雅写代码,写出诗一样的代码

优雅编程

1 判断不是空数组,做一些事情

// bad
if (arr.length !== 0) {
    // todo
}

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

2 使用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
}

3 用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) => arr.some(num => num === n)

4 使用Object.values快速获取对象键值

5 使用Object.keys快速获取对象键名

6 函数参数解构

7 函数参数解构时重命名简化命名

setForm ({aaa_bbb_ccc_ddd: one, eee_fff_ggg: two}) {
    this.one = one
    this.two = two
}

8 巧用可选链操作符( ?. )

原文地址:https://www.cnblogs.com/liaoing/p/14108835.html