繁体   English   中英

JavaScript 条件语句 if/else if/else

[英]JavaScript conditional statements if/else if/else

大家好! 你能帮帮我吗? 我正在尝试使用某些条件,但由于某些原因它们似乎被忽略了。 当我运行代码时,弹出的随机数是 93,它适合第一个声明的语句 (if),但是,即使为 true && true,它也会被忽略并移至最后一个语句。 我不懂为什么... ???

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();

您每次检查时都在计算一个新的匹配百分比,在同一个条件下多次。 你只需要在开始时做一次:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM