在javascript中切换意外的令牌

时间:2012-01-22 21:52:39

标签: javascript switch-statement

我在以下代码中找到了一个意外的令牌。

        switch ( hobby ) {
            case =" painting ":
                message = "Van Gogh was good at that.";
                    break;
            case =" drawing ":
                message = "Hey! Van Gogh did that too.";
                    break;
            case =" playing guitar ":
                message = "Bob Dylan played guitar.";
                    break;
            case =" sleeping in ":
                message = "My favorite hobby in the winter.";
                    break;

            default
        }

有人看到我错过的东西吗?

2 个答案:

答案 0 :(得分:4)

您可以利用函数语义来避免每个break中出现case

var message = (function(){
  switch (hobby) {
    case 'painting':        return 'Van Gogh was good at that.'
    case 'drawing':         return 'Hey! Van Gogh did that too.'
    case 'playing guitar':  return 'Bob Dylan played guitar.'
    case 'sleeping in':     return 'My favorite hobby in the winter.'
  }
}())

然而,表达这种逻辑的最佳方式可能如下:

var messages = {
  'painting':       'Van Gogh was good at that.',
  'drawing':        'Hey! Van Gogh did that too.',
  'playing guitar': 'Bob Dylan played guitar.',
  'sleeping in':    'My favorite hobby in the winter.'
}
var message = messages[hobby]

答案 1 :(得分:3)

您的语法已关闭。在=之后删除case。此外,您需要在:之后加default

有关switch语句的详情,请参阅here