簡體   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