[英]JavaScript conditional statements if/else if/else
Hello guys!大家好! Could you please help me out?
你能帮帮我吗? I am trying to use certain conditions but they seem to be ignored for some reasons.
我正在尝试使用某些条件,但由于某些原因它们似乎被忽略了。 When I ran the code the popped-up random number given was 93 that fitted in the first declared statement (if), but, It got ignored and moved to the last statement even when true && true.
当我运行代码时,弹出的随机数是 93,它适合第一个声明的语句 (if),但是,即使为 true && true,它也会被忽略并移至最后一个语句。 I do not understand why... ???
我不懂为什么... ???
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
if (matchingPercentage() >= 70 && matchingPercentage() <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You guys are meant to be together!");
}
else if( matchingPercentage() >=30 && matchingPercentage() <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchingPercentage() + "%. You better look in another direction!");
}
}
function matchingPercentage() {
var n = Math.random();
var n = Math.floor(n * 100) + 1;
return n;
}
loveMatching();
you're calculating a new match % everytime you check it, multiple times in the same conditional.您每次检查时都在计算一个新的匹配百分比,在同一个条件下多次。 you need to just do it once at the start:
你只需要在开始时做一次:
function loveMatching (name1, name2) {
name1 = prompt ("Enter your name!");
name2 = prompt ("Enter your crush name!");
const matchPercent = matchingPercentage(); // call one time
if (matchPercent >= 70 && matchPercent <=100) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You guys are meant to be together!");
}
else if( matchPercent >=30 && matchPercent <70) {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. Too close to fail!");
}
else {
document.write(" The compability between: " + name1 + " and " + name2 + " is of a " + matchPercent + "%. You better look in another direction!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.