编写动态代码时遇到问题。我正在进行javascript编程课程,而且我在一项任务的最后部分遇到了一些困难。
练习8.2
使用默认值扩展switch-case语句。结果应该 be'那是一种未知的水果。'当变量' 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;}
如何在变量中表达此结果?
我试着这样写:
var result = switch (myFruit);
但这不起作用。
答案 0 :(得分:5)
您可以声明result
变量,并在switch语句的情况下,而不是console.log
ging结果,您可以将值赋给result
变量,如下所示:< / p>
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;
}
答案 1 :(得分:1)
我不会为您写出所有代码,但请指出正确的方向。您需要在变量中设置文本并将其返回:
switch ..
case "something":
var message = "Your message here.";
break;
...
一旦您的开关设置了值,您就可以根据需要使用它。
您不能像操作一样使用switch语句从switch语句返回值。
答案 2 :(得分:1)
你不能像var result = switch (myFruit);
那样调用switch语句,它不是一个函数。您必须将所有开关案例代码移动到一个函数中:
function mySwitchCase(fruit){
var returnResult='';
switch (fruit) {
case "banana":
returnResult="The banana is yellow.";
break;
case "apple":
returnResult="The apple is green.";
break;
case "kiwi":
returnResult"The kiwi is green.";
break;
case "plum":
returnResult"The plum is purple";
break;
default:
returnResult"That is an unknown fruit.";
break;
}
return returnResult;
}
然后你可以这样称呼它:
var result = mySwitchCase(myFruit);
答案 3 :(得分:0)
您可以将结果保存在变量answer
中,然后使用该变量打印出结果;
function fruitSwitcher (myFruit) {
var answer = "That is an unknown fruit.";
switch (myFruit) {
case "banana":
answer = "The banana is yellow.";
break;
case "apple":
answer = "The apple is green.";
break;
case "kiwi":
answer ="The kiwi is green.";
break;
case "plum":
answer = "The plum is purple";
break;
default:
// no really needed
answer ="That is an unknown fruit.";
break;
}
return answer;
}
var myFruit = "pear";
var answer = fruitSwitcher(myFruit);
console.log(answer); //That is an unknown fruit.
上一代码中的默认情况是多余的,因为变量answer
初始化为默认值。如果传入输入中的未知果实,则没有任何开关案例与之匹配,因此answer
变量永远不会更改值,函数将返回默认值。