Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ybning opened this issue Jun 16, 2016 · 1 comment
Open

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

ybning opened this issue Jun 16, 2016 · 1 comment

Comments

@ybning
Copy link
Owner

ybning commented Jun 16, 2016

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);`
@Pines-Cheng
Copy link

顶一个

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants