es常用片段

switch case 优化

::: code-group

function doAction(action) {
    switch (action) {
        case 'hack':
            return 'hack'
        case 'slach':
            return 'slach'
        case 'run':
            return 'run'
        default:
            throw new Error('Invalid action.')
    }
}
function doAction(action) {
    var actions = {
        'hack': () => {
            return 'hack'
        },
        'slach': () => {
            return 'slach'
        },
        'run': () => {
            return 'run'
        }
    }
    if (typeof actions[action] !== 'function') {
        throw new Error('Invalid action.')
    }
    return actions[action]()
}

:::

typeof 优化

::: code-group

:::

enumerable 遍历属性

对象拷贝

Last updated

Was this helpful?