2012-12-13 104 views
2

漂亮的直線前進是我想做的事:的Javascript if語句不工作

  • 如果輸入0,這意味着他們沒有輸入一個數字,它 應該告訴你。
  • 當輸入是7時,應該說你說得對。
  • 還有什麼,它應該告訴你,你錯了。

但是它只是輸出「7是正確」的行,不管輸入是什麼,我無法弄清楚什麼是錯的。

<script type="text/javascript"> 
function problem2() 
{ 
var number = 0; 
var text=document.getElementById("output"); 
number = prompt("Enter a number between 1 and 10 please" , 0); 
if (number = 0) 
    { 
    text.value = "You didn't enter a number!"; 
    } 
if (number = 7) 
    { 
    text.value = "7 is correct!"; 
    } 
else 
    { 
    text.value = "Sorry, ", input, "is not correct!"; 
    } 
} 
</script> 
<input type="button" value="Click here" onclick="problem2()"> 
<input id="output" type="text"> 

回答

6

您正在分配=。使用=====

if(0 == number){ 

    text.value = "You didn't enter a number!"; 
} 

此外,請小心您的支撐位置。 Javascript喜歡自動添加分號到行尾。 Source

+1

除非您確切地知道爲什麼要使用'==',否則您應該更喜歡'===',它不強制類型。另請參見:[在這個問題上這個令人敬畏的stackoverflow答案](http://stackoverflow.com/a/359509/114359) –

+2

在上面的例子中使用'==='不會工作,因爲'提示符的返回值)'是一個字符串。你需要使用'if(number ===「7」)...' –

2

您使用賦值運算符爲你的條件語句,而不是比較符:

if (number = 0) // falsy. Same as if (false) 
    { 
    text.value = "You didn't enter a number!"; 
    } 
if (number = 7) // truthy. Same as if (true) 
    { 
    text.value = "7 is correct!"; 
    } 
else 
    { 
    text.value = "Sorry, ", input, "is not correct!"; 
    } 

或者您可以使用一個開關和組織條件語句更容易一點:

switch (number) { 
    case 0: 
     text.value = "You didn't enter a number!"; 
     break; 

    case 7: 
     text.value = "7 is correct!"; 
     break; 

    default: 
     text.value = "Sorry, ", input, "is not correct!"; 
     break; 
} 
2

這裏是一個代碼一些修復和改進(我評論我改變了什麼):

function problem2(){ 
    //I multiplied by * 1 to work with numbers, also used || to default to 0 in case of NaN 
    var num = (prompt("Enter a number between 1 and 10 please" , 0) * 1) || 0; 
    var msg = ""; 

    if (!num){ //I prefer this over 'num == 0' 
     msg = "You didn't enter a number!"; 
    //you should use 'else if' in this case 
    }else if (num == 7){//'=' is for assignment, use '==' or '===' instead 
     msg = "7 is correct!"; 
    }else{ 
     //you had an undefined var 'input', you probably meant 'num' 
     //you also were connecting var and strings using commas, use '+' instead 
     msg = "Sorry, " + num + " is not correct!"; //added a space in ' is' 
    } 

    //no need to store the element in a var anymore :D 
    document.getElementById("output").value = msg; 
} 

的方法,另外,兩個更改可:

  • 只有一個var(如var something = "", somethingElse = 99;
  • 分配從一開始默認的文本,如var msg = "default"並刪除else

注:我做的一個沒有記錄的變化是重新命名一些變量,我鼓勵所有人停止使用像number, text, string這樣的變量,如果你有這個壞習慣,你最終會錯誤地使用非法的變量名。