我正在做一个练习,但我无法理解为什么我的提示没有被存储为字符串,因此无法与我的 switch case 进行比较
任何输入都返回false:
function getColor(selection) {
switch (selection) {
case 'red':
return true;
case 'green':
return true;
case 'blue':
return true;
default:
return false; //returns false because the user picked an unavailable color
}
}
var colorname = prompt('What color do you want?');
var isAvailable = getColor(colorname);
if (getColor === true) {
console.log('Good news! That color is available');
} else {
console.log('We are sorry, that color is not available');
}
我注意到输入没有被存储为字符串,因为我试图 .toUpperCase
“colorname” var 并且它不会更改为大写。
答案 0 :(得分:1)
您将 getColor(colorname)
的结果存储在 isAvailable
变量中,稍后您将再次比较函数名称而不是使用该变量。
将您的 if 从 if (getColor === true)
更改为 if (isAvailable)
或 if (isAvailable === true)
或其中之一:
if(getColor(colorname) === true)
if(getColor(colorname))