簡體   English   中英

如果兩個數字相等,則使用javascript發出警報

[英]Make an alert with javascript if two numbers are equal

我編寫了這段代碼,以使當我單擊按鈕時,警報提示隨機數是否相等。 2個隨機數必須在1到6之間,並且不能是十進制數。 我在javascript中設置了此功能,但無法正常工作...

 <!DOCTYPE html> <html lang="it"> <head> <meta charset="utf-8"> <title>Numeri Casuali</title> <script type="text/javascript"> function casuali() { var a, b; var a = Math.floor(Math.random() * 6) + 1; var b = Math.floor(Math.random() * 6) + 1; if (a == b) { alert("Equals") } else { alert("Not Equals") } } </script> </head> <body> <button type="button" onclick=”casuali()”>Clicca qui</button> </body> </html> 

您的變量聲明有誤,JavaScript中沒有int ,就像您可能從Java或其他類型的語言中知道的那樣。 在javascript中,我們使用varletconst js是松散類型的

int a = Math.floor(Math.random() * 6) + 1;
int b = Math.floor(Math.random() * 6) + 1;

改成

var a = Math.floor(Math.random() * 6) + 1;
var b = Math.floor(Math.random() * 6) + 1;

並刪除var a,b; ,或簡單地使用

a = Math.floor(Math.random() * 6) + 1;
b = Math.floor(Math.random() * 6) + 1;

同時它else沒有else ()

完整的工作代碼:

function casuali() {
    var a, b;
    a = Math.floor(Math.random() * 6) + 1;
    b = Math.floor(Math.random() * 6) + 1;
    if (a == b) {
        console.log("Equals")
    } else {
        console.log("Not Equals")
    }
}

有2個問題:1-從以下代碼中刪除int:

 int a = Math.floor(Math.random() * 6) + 1; int b = Math.floor(Math.random() * 6) + 1; 

2-從以下內容中刪除if():

 } else if() { alert("Not Equals") } 

因此正確的代碼是:

 function casuali(){ var a,b; a = Math.floor(Math.random() * 6) + 1; b = Math.floor(Math.random() * 6) + 1; if (a==b) { alert("Equals") } else { alert("Not Equals") } } 

你的問題顯然是這個

onclick=”casuali()”

需要為onclick="casuali()"

您的JavaScript代碼中有一些拼寫錯誤。

這是正確的版本:

function casuali(){ 
   var a,b;

   a = Math.floor(Math.random() * 6) + 1; 
   b = Math.floor(Math.random() * 6) + 1;

    if (a==b) { 
        alert("Equals");
     } else { 
         alert("Not Equals");
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM