你好,我是javascript的新手,正在尝试运行以下命令
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else (age > 19) {
document.write("you can already drink");
}
我似乎什么都没显示,但是如果我更改代码以删除else语句并将===
更改为==
,我的代码就会运行。这是我摆脱else语句和===
运算符后运行时的样子。
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age == 19) {
document.write("you can finally drink");
}
我正在尝试使第一段代码运行,但无法运行。页面为空,没有提示。有人帮忙。
答案 0 :(得分:1)
您的代码中有一些错误:
1) prompt
方法返回string
否number
,因此:
使用==
代替===
:
else if (age == 19) {
PS:(19 =='19');是true
但是(19 ==='19');是false
OR 将age
转换为数字:
else if (Number(age) === 19) {
2)您不应对else
使用条件,因此必须像这样更改else
:
else { document.write("you can already drink"); }
var age = prompt("What is your age");
if (age < 19) { document.write("You can't drink"); }
else if (Number(age) === 19) { document.write("you can finally drink"); }
else { document.write("you can already drink"); }
答案 1 :(得分:0)
您的问题是最后的else陈述。您将条件放在else后面,这不起作用。如果仅在另一个条件下添加条件。您可以通过删除以下条件来解决此问题:
var age = prompt("What is your age");
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
答案 2 :(得分:0)
首先,您需要确定“ ==”和“ ===”之间的区别。在this中,您可以得出结论
JavaScript具有严格和类型转换相等性比较。为了严格相等,要比较的对象必须具有相同的类型,并且: 当两个字符串在相同位置具有相同的字符序列,相同的长度和相同的字符时,它们严格相等。 当两个数字在数值上相等时(具有相同的数值)严格相等。 NaN不等于任何事物,包括NaN。正零和负零彼此相等。 如果两个布尔操作数都为true或均为false,则它们严格相等。 如果两个对象引用相同的对象,则它们严格相等。 Null和Undefined类型为==(但不是===)。 [即(Null == Undefined)为true,但(Null === Undefined)为false]
其次,带有条件的“ else”始终写为“ else if” ... else是一个块,当以上条件都不为真(即都不为真)时运行。.here中读取更多信息
答案 3 :(得分:0)
您在上一个else
语句中似乎有一些逻辑错误。如果前两个条件都不为真,那么从逻辑上讲,最后一个条件必须为真。 else
没有任何条件。就以前的条件而言,这仅仅是 else 。否则,您将不得不再次使用else if()
,但是如前所述,如果两个条件都不成立,则无论在此示例中,最后一个条件都必须为真。因此, else 最有意义。
示例:
if (age < 19) {
document.write("You can't drink");
}
else if (age === 19) {
document.write("you can finally drink");
}
else {
document.write("you can already drink");
}
与您的操作员有关的另一件事。 ==
表示等于,可用于比较不同的类型。即您可以将 number 类型与 string 类型进行比较,如果它们都具有相同的值,则该语句为true。但是,===
是一个严格的等号,表示要比较的事物必须具有相同的值和相同的类型。
示例:
var x = 5; //number
var y = '5'; //string
if(x == y) {
//true, because they are equal, both has the value 5
}
if(x === y) {
//false, because even though they are equal in value, they are not the same type
}
var a = 8; //number
var b = 8; //number
if(a === b) {
//true, because they are both equal, and the same type
}
因此,为了澄清,
==
检查值是否等于 ,无论类型如何。
===
检查值是否等于 并且具有相同的 type 。
关于运营商here的更简单的文档。