我永远不会理解这些事情,所以我需要向正确的方向努力。 我有一个需要挑选水果颜色的函数我选择了Switch case语句。问题是我不知道如何从声明中得到结果。也许我应该得到一个If / else语句?这是代码:
function fruitColor(fruit) {
switch(color) {
case "apple" : green;
break;
case "banana" : yellow;
break;
case "kiwi" : green;
break;
case "plum" : red;
break;
}
}
var result = fruitColor(plum);
我无法得到结果,我不确定我是否需要'返回'值或类似的东西。推进正确的方向将是值得赞赏的。 谢谢advancve。 此致,托马斯
答案 0 :(得分:5)
return语句结束函数执行并指定要返回给函数调用者的值。 return MDN
除了不返回值之外,还有一些失误。 return
是从函数发回值的工具,但为了实现这一点,不会发生错误。就目前而言,变量color
在switch语句中使用,但它不存在,可能是因为它应该是fruit
,反之亦然。此外,case语句的结果代码中的值基本上只是对变量的引用,如果没有名为green
的变量,那么它就是未定义的。也许你的意思是“绿色”。
function fruitColor(fruit) {
//note that there was no value color here, there was only the accepted
//parameter fruit, which should either be used or changed to color
switch(color) {
case "apple" :
//needs quotes, green with no quotes is a variable reference
"green";
//note that simply using the string "green" doesn't accomplish anything though
//what we really need to do is send a value back, and in JavaScript you
//use the return keyword for that followed by the returning value
return "green";//like this
break;
case "banana" : "yellow";//^
break;
case "kiwi" : "green";//^
break;
case "plum" : "red";//^
break;
}
}
var result = fruitColor("plum");//needs quotes, plum would be a variable refernce
就个人而言,我更喜欢这类工作的字典。
var fruitColors = {
apple : "green",
banana : "yellow",
kiwi : "green",
plum : "red"
};
var plumColor = fruitColors["plum"];//red
答案 1 :(得分:2)
编码时,您希望始终保持代码的良好性能。既然我说过,让我给你一些解决这类问题的方法:
首先让我们使用您当前的解决方案并使其正常运行。
function fruitColor(fruit) {
switch(color) {
case "apple" :
return 'green';
break;
case "banana" :
return 'yellow';
break;
case "kiwi" :
return 'green'
break;
case "plum" :
return 'red';
break;
}
}
var result = fruitColor(plum);
这个使用你的开关并且过早地返回,有效。
然而,它不是攻击此类问题的最佳方法,因为它会生成代码分支,意味着更多内存用于存储和评估代码,另一种方法是使用带有水果和颜色的对象。 / p>
function fruitColor(fruit) {
var fruits = {
apple : 'green',
banana : 'yellow',
kiwi : 'green',
plum : 'red'
};
return fruits[fruit] || 'not found';
}
var result = fruitColor('plum');
此代码依赖于内存数据库,工作速度快,分叉较少,但也取决于搜索。
答案 2 :(得分:0)
我想添加@Travis J帖子的后续内容。
在这里,我想强调一下如何将参数放入switch语句。参数变量fruit
和color
带有一个参数。如果要将参数从函数fruitColor
提取到switch语句中,请使用相同的参数变量名称。也就是说,两者都使用fruit
,或者两者都使用color
。
function fruitColor(fruit) {
//note that there was no value color here, there was only the accepted
//parameter fruit, which should either be used or changed to color
switch(color) {
case "apple" :
"green";
return "green";//like this
break;
case "banana" : "yellow";//^
break;
case "kiwi" : "green";//^
break;
case "plum" : "red";//^
break;
}
}
var result = fruitColor("plum");
答案 3 :(得分:0)
这是我的switch功能实现
node:alpine
答案 4 :(得分:-2)
首先在switch语句中你必须使用fruit参数而不是颜色,然后你需要一个变量来存储你的选择
function fruitColor(fruit) {
switch(fruit) {
case "apple" : result = green;
break;
case "banana" : result = yellow;
break;
case "kiwi" : result = green;
break;
case "plum" : result = red;
break;
}
return result;
}
var result = fruitColor(plum);