简体   繁体   English

使用对象替换switch语句

[英]Using an object to replace the switch statement

I found the following exemple on the jqfundamentals site. 我在jqfundamentals网站上找到了以下示例。 It seems to me that the else statement is unnecessary/wrong. 在我看来,else陈述是不必要的/错误的。 So what am I missing ? 那我想念什么呢?

var stuffToDo = {
    'bar' : function() {
        alert('the value was bar -- yay!');
    },

    'baz' : function() {
        alert('boo baz :(');
    },

    'default' : function() {
        alert('everything else is just ok');
    }
};

if (stuffToDo[foo]) {
    stuffToDo[foo]();
} else {
    stuffToDo['default']();
}

It's just checking that stuffToDo[foo] exists... 只是在检查是否存在stuffToDo[foo] ...

and If it doesn't call the 'default' 如果没有调用'default'

Not sure that I think replacing the switch statement is necessary or good, let alone a fundamental of javascript... 我不确定我认为替换switch语句是否必要或很好,更不用说JavaScript的基础了...

如果foo"moo" ,则将stuffToDo['default']() (以避免引发异常)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM