【问题标题】:JavaScript switch function [closed]JavaScript开关功能[关闭]
【发布时间】:2015-02-24 20:24:19
【问题描述】:

我试图让这段代码运行,但它给了我一个错误,说“输入意外结束”。你能帮忙吗?提前致谢。

var getReview = function (movie) {
switch (movie) {
case "Toy Story 2":
    return "Great story. Mean prospector.";
    break;
case "Finding Nemo" :
    return "Cool animation, and funny turtles.";
    break;
case "The Lion King" :
    return "Great songs.";
    break;
default : 
    return "I dont know!"; 
    break;
};

【问题讨论】:

  • 你需要一个右括号}。
  • 你也不需要最后的 break 语句,因为它是 switch 的结束
  • 函数末尾需要一个}
  • ...您还需要一个能够突出显示此类语法错误的优秀 IDE。
  • 另外请注意,如果这将是一个很大的列表,您希望将答案存储在 JSON 之类的东西中,而不是存储在一个可笑的长 switch 语句中。

标签: javascript function switch-statement


【解决方案1】:

您的函数似乎缺少右括号:

var getReview = function (movie) {
    switch (movie) {
    case "Toy Story 2":
        return "Great story. Mean prospector.";
        break;
    case "Finding Nemo" :
        return "Cool animation, and funny turtles.";
        break;
    case "The Lion King" :
        return "Great songs.";
        break;
    default : 
        return "I dont know!"; 
        break;
    };
};  // <-- here

还请注意,在return 之后有一个break 或在switch 块的末尾有一个分号是没有意义的。您可以将上述内容简化为:

var getReview = function (movie) {
    switch (movie) {
    case "Toy Story 2":
        return "Great story. Mean prospector.";
    case "Finding Nemo" :
        return "Cool animation, and funny turtles.";
    case "The Lion King" :
        return "Great songs.";
    default : 
        return "I dont know!"; 
    }
};

【讨论】:

  • 天哪,谢谢!我今天一定太累了。我很感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多