我正在编写一个可以制造无钥匙汽车的代码。因此,当您键入年龄时,应该输入以下内容:
1)如果他们说自己未满18岁,请回答: “抱歉,您还太年轻,无法驾驶这辆车。请关机”
2)如果他们说自己18岁,请回答: “恭喜您驾驶的第一年。祝您旅途愉快!”
3)如果他们说年满18岁,请回答: “加电。享受旅程!”
我应该使用JS条件,例如: 如果, 其他, 否则
当我说“ else”(第三个条件)时,如果condition1为false而condition2为false,则应执行代码块。因此,它们都是错误的。 我尝试使用'else if'代替'else',但是它起作用了,但是我不明白它们之间的区别。
var age = prompt("Good day! What is your age?:");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else (age > 18) {
alert("Powering On. Enjoy the ride!");
}
我期待的是带有正确文本的警报消息,但是它给我一个错误的最后一个'else': 未捕获到的SyntaxError:意外令牌{
答案 0 :(得分:1)
否则不应该有条件,因为else的代码在没有条件匹配时就执行。
编辑:如Maheer Ali所述,您还应该将var age
转换为int。
var age = prompt("Good day! What is your age?:");
age = parseInt(age);
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else {
alert("Powering On. Enjoy the ride!");
}
答案 1 :(得分:0)
else
不应具有以下条件:(删除(age > 18)
部分)
还要确保将字符串值转换为int进行比较(<> =)
var age = prompt("Good day! What is your age?:");
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
} else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
} else {
alert("Powering On. Enjoy the ride!");
}
答案 2 :(得分:0)
删除您的其他
中的疾病var age = prompt("Good day! What is your age?:");
// Betwen 0 and 17 years old
if (age < 18) {
alert("Sorry, you are too young to drive this car. Powering off");
}
// Exactly 18 years old
else if (age === 18) {
alert("Congratulations on your first year of driving. Enjoy the ride!");
}
// We don't care about her age here :-D
else {
alert("Powering On. Enjoy the ride!");
}