Skip to content

使用命令对象代替switch语句的写法示例 #8

Open
@ybning

Description

@ybning

switch 方法

function testSwitch(name) {
    switch (name) {
        case '1':
            return '1';
            break;
        case '2':
            return '2';
            break;
        case '3':
            return '3';
            break;
        default:
            return false;
            break;
    }
}

使用命令对象

function testFn(name) {
    var names = {
        '1': function() {
            return '1';
        },
        '2': function() {
            return '1';
        },
        '3': function() {
            return '3';
        }
    };
    if (typeof names[name] !== 'function') {
        return false;
    }
    return names[name]();
}

测试结果

var result1 = testSwitch('1');
var result2 = testFn('2');
console.info(result1, result2);`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions