2013-06-02 49 views
-1

我今天就開始使用javascript了。嘗試與非常基本的,並堅持與If Else循環。Javascript if if condition run time failure

 


    var input = prompt("type your name"); //variable stores the value user inputs 
    var outout = tostring(input); // the input value is changed to string datatype and stored in var output 
    alert(output);//supposed to display the value which it doesn't 

    if(output == "Tiger") 
    {alert("It is dangerous"); 
    } 
    Else 
    {alert("all is well"); 
    }//I only get a blank page 
    

如果我省略了行var輸出= tostring(輸入)並嘗試顯示具有輸入值的警報框,我會看到警報框。但之後我只能看到一個空白頁面。 If Else循環根本不起作用。我正在使用記事本++。也在Dreamweaver中檢查。沒有編譯錯誤。我究竟做錯了什麼? 對不起,這個基本的問題,謝謝你的回覆。

問候, TD

+0

的Javascript關鍵字和標識符是區分大小寫的。 – SLaks

回答

0

你的代碼中存在以下問題:

var input = prompt("type your name"); 
var outout = tostring(input); 
// Typo: outout should be output 
// tostring() is not a function as JavaScript is case-sensitive 
// I think you want toString(), however in this context 
// it is the same as calling window.toString() which is going to 
// return an object of some sort. I think you mean to call 
// input.toString() which, if input were not already a string 
// (and it is) would return a string representation of input. 
alert(output); 
// displays window.toString() as expected. 
if(output == "Tiger") 
{alert("It is dangerous"); 
} 
Else // JavaScript is case-sensitive: you need to use "else" not "Else" 
{alert("all is well"); 
}//I only get a blank page 

我懷疑你想要的東西是這樣的:

var input = prompt("type your name"); 
alert(input); 
if (input === "Tiger") { 
    alert("It is dangerous"); 
} else { 
    alert("all is well"); 
} 
+0

它可以在我刪除var outout = toString(input)之後生效。 – user1976929

+0

非常感謝皮特的回覆。 Outout是一個錯字。它在我省略<< var output = toString(input); >>之後立即生效。我沒有編程背景,所以很抱歉讓你們失望失望。 – user1976929

1

你行

tostring(input);

應該

toString(input);

toString()方法有一個大寫字母S

另外,你的輸出變量被稱爲「輸出」。不知道這是否是一個錯字...

不僅如此,你的Else也應該有一個小的e。所有JavaScript關鍵字都區分大小寫。

+0

@ Doorknob剛剛注意到。感謝+1 :) – imulsion

+1

另外,'toString()'是一個實例方法。 – SLaks

+0

我忽略了區分大小寫的部分...將tostring更改爲toString,然後出現第二個警告框。但我不確定什麼是實例方法...我沒有編程背景。對於疏忽感到抱歉。非常感謝答覆。 – user1976929

1

您不必將提示的結果轉換爲字符串,它已經是字符串了。它實際上是

input.toString() 

Else是小寫的,正確的是else

所以,你可以使用這樣

var input = prompt("Type your name"); 

if (input == "Tiger") 
{ 
    alert("Wow, you are a Tiger!"); 
} 
else 
{ 
    alert("Hi " + input); 
} 

請注意,如果你輸入tiger(小寫),你最終會在else。如果要比較的字符串不區分大小寫,你可以這樣做:

if (input.toLowerCase() == "tiger") 

然後甚至tIgEr會工作。

+0

我省略了var outout = toString(input);它的工作。謝謝。 – user1976929

+0

.toString和Convert.toString()....你能解釋一下有什麼不同嗎?謝謝。 – user1976929

+0

JavaScript中沒有'Convert.toString'。你的意思是C#'Convert.ToString()'? http://msdn.microsoft.com/en-us/library/system.convert.tostring.aspx – BrunoLM