我正试图使一个功能,涉及开关(),并给我具体的答案,随机生成的数字。不知怎么的,我的函数没有运行它应该运行的情况。它只给我默认的情况,不管数字是多少。
这是我的代码:
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);
}
}
开关不是这样工作的。它比较每个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]);
}
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
中有比较表达式
当声明一个switch时,所使用的变量将与每种情况进行比较,因此不需要求值。
还可以帮助将答案从'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);
}
}
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;