优雅的编写 Javascript

摘抄自https://zhuanlan.zhihu.com/p/28910636

使用有意义的变量名

Bad

const addr = 'http://google.com?firstVal=a&secondVal=b'
const valueRegex = /firstVal=(.+?)&secondVal=(.+?)/
saveVals(
    addr.match(valueRegex)[1],
    addr.match(valueRegex)[2]
)

Good

const addr = 'http://google.com?firstVal=a&secondVal=b'
const valueRegex = /firstVal=(.+?)&secondVal=(.+?)/
const [, valueA, valueB] = addr.match(valueRegex) || []
saveVals(valueA, valueB)

保持函数功能单一

Bad

function emailClients(clients) {
    clients.forEach(client => {
        const clientRecord = database.lookup(client)
        if (clientRecord.isActive()) {
            email(client)
        }
    })
}

Good

function emailClients(clients) {
    clients
        .filter(isActiveClient)
        .forEach(email)
}

function isActiveClient(client) {
    const clientRecord = database.lookup(client)
    return clientRecord.isActive()
}

使用默认变量替代短路运算或条件

Bad

function createMicrobrewery(name) {
    const breweryName = name || 'default name'
}

Good

function createMicrobrewery(breweryName = 'default name') {

}

results matching ""

    No results matching ""