Javascript if else条件运行时失败

Javascript if else condition run time failure

本文关键字:运行时 失败 条件 else if Javascript      更新时间:2023-09-26

我今天已经开始使用javascript了。尝试使用最基本的If Else循环,但被卡住了。

<>之前Var input = prompt("输入你的名字");//变量存储用户输入的值Var outout = tostring(输入);//将输入值更改为字符串数据类型并存储在var output中Alert (output);//应该显示它没有显示的值if(output == "Tiger"){alert("这是危险的");}其他的{alert("一切正常");}//我只得到一个空白页之前

如果省略var output = tostring(input)行,并尝试显示带有输入值的警告框,则会得到警告框。但在那之后,我只能得到一张白纸。If Else循环根本不起作用。我用的是notepad++。在Dreamweaver中也检查过。没有编译错误。我做错了什么?很抱歉问了这么一个基本的问题,谢谢你的回复。

问候,TD

你的台词

tostring(input);

应该

toString(input);

toString()方法有一个大写S

同样,你的输出变量被称为"outout"。不知道是不是打错了…

不仅如此,您的Else也应该有一个小的e。所有JavaScript关键字都区分大小写

您不必将提示的结果转换为字符串,它已经是字符串了。实际上应该是

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也可以工作

你的代码有以下问题:

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");
}