我正在尝试创建一个涉及switch()的函数,并根据特定的随机生成的数字给出答案。不知怎的,我的函数没有运行它应该运行的情况。它只给出了默认情况,无论数字是多少。
这是我的代码:
var i;
var girl;
function response() {
var girl = prompt("What girl do you like?");
var r = (Math.random() * (3 - 1 + 1) + 1).toFixed(0);
var i = r;
switch(i) {
case (i == 1):
alert(girl + " likes you as a friend.");
break;
case (i == 2):
alert(girl + " does not really like you.");
break;
case (i == 3):
alert(girl + " has a crush on you.");
break;
case (i == 4):
alert(girl + " wants you to ask her out.");
break;
default:
console.log(i);
}
}
答案 0 :(得分:4)
这不是开关的工作原理。它会将每个case
的值与switch
进行比较。
现在基本上,它将i
的值多次与布尔值(例如i == 1
的结果)进行比较。
此外,通过将静态值的算术添加到值中,您的随机性不会变得更随机。您应该将其替换为4
。你也应该使用像Math.ceil()
这样的东西(因为你忽略了0
值,这也许不是一个好主意),而不是toFixed()
返回一个字符串。
您也不需要围绕值进行比较的括号。如果您知道随机数的范围,您可能也不需要默认情况(因为您已经涵盖了所有可能性)。
您也可以直接使用r
,无需重新分配。
您的变量也是您的函数的本地变量,因此可能不需要它们在顶部。
以下是我将如何重写:
function response() {
var girl = prompt("What girl do you like?");
var r = Math.floor(Math.random() * 4);
switch(r) {
case 0:
alert(girl + " likes you as a friend.");
break;
case 1:
alert(girl + " does not really like you.");
break;
case 2:
alert(girl + " has a crush on you.");
break;
case 3:
alert(girl + " wants you to ask her out.");
break;
}
}
......甚至......
function response() {
var answerSuffixes = [
" likes you as a friend.",
" does not really like you.",
" has a crush on you.",
" wants you to ask her out."
];
var girl = prompt("What girl do you like?");
var r = Math.floor(Math.random() * answerSuffixes.length);
alert(girl + answerSuffixes[r]);
}
答案 1 :(得分:1)
Javascript中的case语句已经在目标i
上匹配:
switch(i) {
case 1:
alert(girl + " likes you as a friend.");
break;
case 2:
alert(girl + " does not really like you.");
break;
case 3:
alert(girl + " has a crush on you.");
break;
case 4:
alert(girl + " wants you to ask her out.");
break;
default:
console.log(i);
}
因此,不需要在每个case
中使用比较表达式。
答案 2 :(得分:0)
switch
正在比较严格。
你需要
switch (i) {
case 1:
alert(girl + " likes you as a friend.");
break;
或者
switch (true) {
case i === 1:
alert(girl + " likes you as a friend.");
break;
答案 3 :(得分:0)
当您声明一个开关时,将使用的变量与每种情况进行比较,因此不需要进行评估。
为了保持变量类型的检查,将'r'的答案解析为整数也可能有帮助。
function response() {
var girl = prompt("What girl do you like?");
var r = parseInt((Math.random() * (3 - 1 + 1) + 1).toFixed(0));
var i = r;
switch(i) {
case 1:
alert(girl + " likes you as a friend.");
break;
case 2:
alert(girl + " does not really like you.");
break;
case 3:
alert(girl + " has a crush on you.");
break;
case 4:
alert(girl + " wants you to ask her out.");
break;
default:
console.log(i);
}
}