Switch中的Return语句

时间:2014-02-25 09:33:42

标签: javascript switch-statement

我希望能够在以下switch语句中返回每个评论,目前只返回第一个评论。可能是什么问题?

var getReview = function (food) {        
    switch (food) {    
        case "Pancakes":
            console.log("The Kids love it");
            break;           
        case "Pasta":
            console.log("Popular Italian food");
            break;                
        case "Naan":
            console.log("Asian bread");
            break;            
        default:
            console.log("Don't like food?");
            break;
    }

    return food;
};

2 个答案:

答案 0 :(得分:3)

 var getReview = function (food) {
     var review;
     switch (food) {

         case "Pancakes":
             review = "The Kids love it";
             break;

         case "Pasta":
             review = "Popular Italian food";
             break;


         case "Naan":
             review = "Asian bread";
             break;

         default:
             review = "Don't like food?";
             break;
     }
     console.log(review);
     return review;
 };

var review = getReview('Pancakes'); //Return value = The Kids love it, Console = The Kids love it

答案 1 :(得分:1)

我不确定你想要什么,但是,定义这样的函数会很有用:

var getReview = function (food) {
  switch (food){
  case "Pancakes":
    return "The Kids love it";
  case "Pasta":
    return "Popular Italian food";
  case "Naan":
    return "Asian bread";
  default:
    return "Don't like food?";
  }
};

在你有这样的功能后,你可以得到如下结果:

getReview('Pancakes');
=> 'The Kids love it'

getReview('Paster');
=> 'Popular Italian food'
...