2013-06-02 53 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