如何在变量中写出我的答案?

Bjo*_*now 0 javascript switch-statement

编写动态代码时遇到问题.我正在进行javascript编程课程,我正在与一项任务的最后部分进行一些斗争.

练习8.2

使用默认值扩展switch-case语句.结果应该是'那是一种未知的果实'.当变量'myFruit'具有未知值时.回答'myFruit = pear'的结果.

在下面编写代码并将答案放入变量ANSWER中.

var myFruit = "pear";
switch (myFruit) {
  case "banana":
  console.log("The banana is yellow.");
  break;
  case "apple":
  console.log("The apple is green.");
  break;
  case "kiwi":
  console.log("The kiwi is green.");
  break;
  case "plum":
  console.log("The plum is purple");
  break;
  default:
  console.log("That is an unknown fruit.");
  break;}
Run Code Online (Sandbox Code Playgroud)

如何在变量中形成此结果?

我试着像这样写:

var result = switch (myFruit);
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

Ama*_*yla 5

您可以声明result变量,并在switch语句的情况下,而不是console.logging结果,您可以将值result赋给变量,如下所示:

var myFruit = "pear";
var result;
switch (myFruit) {
  case "banana":
      result = "The banana is yellow.";
      break;
  case "apple":
      result = "The apple is green.";
      break;
  case "kiwi":
      result = "The kiwi is green.";
      break;
  case "plum":
      result = "The plum is purple";
      break;
  default:
      result = "That is an unknown fruit.";
      break;
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/uqxtmc25/